package com.yanqu.road.server.manger.activity.dafuweng;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.dafuweng.*;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.activity.dafuweng.eDaFuWengBuildingType;
import com.yanqu.road.entity.enums.activity.dafuweng.eDaFuWengCardType;
import com.yanqu.road.entity.enums.activity.dafuweng.eDaFuWengEventType;
import com.yanqu.road.entity.enums.activity.dafuweng.eDaFuWengParamType;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.log.LogBuy;
import com.yanqu.road.entity.log.LogDFWDamage;
import com.yanqu.road.entity.log.LogDFWRebateReward;
import com.yanqu.road.entity.log.LogDFWRoll;
import com.yanqu.road.entity.player.UserBagItem;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.bussiness.activity.DFWActivityBussiness;
import com.yanqu.road.logic.helper.CalcPowerResult;
import com.yanqu.road.logic.helper.PowerHelper;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.monopoly.CrossMonopolyProto;
import com.yanqu.road.pb.monopoly.MonopolyProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.BagModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PlayerModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.manger.CrossReqMgr;
import com.yanqu.road.server.manger.CrossUnionServerGroupMgr;
import com.yanqu.road.server.manger.VipMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.curio.CurioMgr;
import com.yanqu.road.server.manger.activity.dafuweng.building.BaseDFWBuilding;
import com.yanqu.road.server.manger.activity.dafuweng.entiety.CollectEventResult;
import com.yanqu.road.server.manger.config.MallRechargeConfigMgr;
import com.yanqu.road.server.manger.config.UnionConfigMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.WorldMessageMgr;
import com.yanqu.road.server.manger.system.CommonMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.pb.DaFuWengPb;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.pb.WorldMessagePb;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author wpj
 * @Date 2021/1/5
 */
public class DaFuWengMgr extends TempMgr {

    /**
     * 地图总格子数
     */
    public static final int StepsNum = 72;
    private static DFWConfig dfwConfig;
    private static Map<Integer, Map<Long, DFWUserData>> userDataMap = new ConcurrentHashMap<>();
    private static Object lockObject = new Object();
    private static Map<Integer, Map<String, MonopolyProto.UnionDataMsg>> unionMsgMap = new ConcurrentHashMap<>();
    /**
     * 重掷色子默认权重
     */
    private static final int reRollWeightDefault = 600;

    public static Object getLockObject() {
        return lockObject;
    }

    public static synchronized void addCollection(int activityId, String unionId, int taskId, int addTimes) {
        Map<Long, CrossUnionMember> unionMemberMap = CrossUnionMgr.getUnionMemberMap(unionId);
        for (CrossUnionMember unionMember : unionMemberMap.values()) {
            if (unionMember.getServerId() == GameServer.getInstance().getServerId()) {
                DFWUserData userData = DaFuWengMgr.getUserData(getDfwConfig().getActivityInfo().getActivityId(), unionMember.getUserId());
                Map<Integer, Integer> rewardCollectionMap = userData.getRewardCollectionMap();
                if (!rewardCollectionMap.containsKey(taskId)) {
                    rewardCollectionMap.put(taskId, 0);
                }
                int count = rewardCollectionMap.get(taskId);
                rewardCollectionMap.put(taskId, count + addTimes);
                userData.setUpdateOption();
            }
        }
    }

    public static void updateUnionMsg(int activityId,String unionId, MonopolyProto.UnionDataMsg unionMsg) {
        Map<String, MonopolyProto.UnionDataMsg> msgMap = unionMsgMap.get(activityId);
        if (msgMap == null) {
            msgMap = new ConcurrentHashMap<>();
            unionMsgMap.put(activityId, msgMap);
        }
        msgMap.put(unionId, unionMsg);
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean save() {
        for (Map<Long, DFWUserData> map : userDataMap.values()) {
            for (DFWUserData userData : map.values()) {
                if (userData.isInsertOption()) {
                    DFWActivityBussiness.addDFWUserData(userData);
                } else if (userData.isUpdateOption()) {
                    DFWActivityBussiness.updateDFWUserData(userData);
                }
            }
        }
        return true;
    }

    public static boolean isActivityInShowTime() {
        if (dfwConfig == null) {
            return false;
        }
        return ActivityMgr.activityInShowTime(dfwConfig.getActivityInfo());
    }

    public static List<DFWEvent> getReachEvents(DFWConfig dfwConfig, eDaFuWengBuildingType buildingType) {
        return getEvents(dfwConfig, dfwConfig.getDfwBuildingConfigMap().get(buildingType.getValue()).getReachEventList());
    }

    public static List<DFWEvent> getPassEvents(DFWConfig dfwConfig, eDaFuWengBuildingType buildingType) {
        return getEvents(dfwConfig, dfwConfig.getDfwBuildingConfigMap().get(buildingType.getValue()).getPassEventList());
    }

    public static List<DFWEvent> getEvents(DFWConfig dfwConfig, List<Map<Integer, Integer>> events) {
        if (events == null || events.size() == 0) {
            return new ArrayList<>();
        }
        List<DFWEvent> dfwEventList = new ArrayList<>();
        Random random = new Random();
        for (Map<Integer, Integer> map : events) {
            List<Integer> weightList = new ArrayList<>();
            List<Integer> eventIdList = new ArrayList<>();
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                eventIdList.add(entry.getKey());
                weightList.add(entry.getValue());
            }

            if (eventIdList.size() == 0) {
                continue;
            }

            int eventId = eventIdList.get(RandomHelper.getRandomIndexByWeight(weightList, random));
            dfwEventList.add(dfwConfig.getDfwEventMap().get(eventId));
        }
        return dfwEventList;
    }

    /**
     * 获取玩家对象数据 不存在则创建对象
     */
    public static DFWUserData getUserData(int activityId, long userId) {

        if (!userDataMap.containsKey(activityId)) {
            synchronized (lockObject) {
                if (!userDataMap.containsKey(activityId)) {
                    // 读库
                    Map<Long, DFWUserData> map = DFWActivityBussiness.getDFWUserDataMap(activityId);
                    userDataMap.put(activityId, map);
                }
            }
        }
        Map<Long, DFWUserData> map = userDataMap.get(activityId);

        if (!map.containsKey(userId)) {
            synchronized (lockObject) {
                if (!map.containsKey(userId)) {
                    // 生成数据
                    DFWUserData dfwUserData = new DFWUserData();
                    dfwUserData.setUserId(userId);
                    dfwUserData.setActivityId(dfwConfig.getActivityInfo().getActivityId());
                    dfwUserData.setGoldScore(0);
                    dfwUserData.setPositionIndex(0);
                    dfwUserData.setDollId(dfwConfig.getDefaultDollId());
                    dfwUserData.setVehicleId(0);
                    dfwUserData.setVehicleMoveTimes(0);
                    dfwUserData.setEnergy(dfwConfig.getInitEnergy());
                    dfwUserData.setLastRecoveryTime(0);
                    dfwUserData.setComplete(true);
                    dfwUserData.setFreeBattleTimes(0);

                    // 添加默认人偶
                    List<DFWDollData> dollDataList = new ArrayList<>();
                    DFWDollData userDoll = new DFWDollData(dfwConfig.getDefaultDollId(), 0);
                    dollDataList.add(userDoll);
                    dfwUserData.setDollList(dollDataList);

                    dfwUserData.setYongBingTimes(0);
                    dfwUserData.setUserSecretRoadList(new ArrayList<>());
                    dfwUserData.setRewardCollectionMap(new ConcurrentHashMap<>());
                    dfwUserData.setRebateRewardRecord(new ArrayList<>());
                    dfwUserData.setDfwGodDataList(new ArrayList<>());
                    dfwUserData.setLastResetTime(System.currentTimeMillis());

                    dfwUserData.setInsertOption();

                    map.put(userId, dfwUserData);
                }
            }
        }

        DFWUserData userData = map.get(userId);

        // 每日重置
        long today = LocalDateTimeHelper.getZeroTimeTimeStamp();
        if (today > userData.getLastResetTime()) {
            userData.setRebateRewardRecord(new ArrayList<>());
            userData.setLastResetTime(System.currentTimeMillis());
        }

        return userData;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static DFWConfig getDfwConfig() {
        return dfwConfig;
    }

    public static void setDfwConfig(DFWConfig dfwConfig) {
        DaFuWengMgr.dfwConfig = dfwConfig;
    }

    public static void reloadActivityData() {
        getLogger().info("reload DaFuWeng start");

        DFWConfig tmpDFWConfig = new DFWConfig();

        // 活动信息 activityInfo
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.DaFuWeng.getValue());
        if (openActivityInfoList.size() == 0) {
            getLogger().info("no DaFuWeng in show time");
            return;
        }
        tmpDFWConfig.setActivityInfo(openActivityInfoList.get(0));

        int tmpActivityId = tmpDFWConfig.getActivityInfo().getActivityId();
        tmpDFWConfig.setDfwBuildingConfigMap(DFWActivityBussiness.getDFWBuildingConfigMap(tmpActivityId));
        tmpDFWConfig.setDfwEventMap(DFWActivityBussiness.getDFWEventConfigMap(tmpActivityId));
        tmpDFWConfig.setBossConfigMap(DFWActivityBussiness.getDFWBossConfigMap(tmpActivityId));
        tmpDFWConfig.setDfwMapConfigList(DFWActivityBussiness.getDFWMapConfigList(tmpActivityId));

        // 初始化技能配置
        Map<eDaFuWengEventType, List<DFWEvent>> tmpSkillMap = buildSkillMap(tmpDFWConfig.getDfwEventMap());
        tmpDFWConfig.setSkillMap(tmpSkillMap);

        Map<eDaFuWengParamType, DFWParamConfig> paramConfigMap = DFWActivityBussiness.getDFWParamConfigMap(tmpActivityId);
        // 体力配置
        tmpDFWConfig.setMaxEnergy(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_MAX_ENERGY).getValue()));
        tmpDFWConfig.setInitEnergy(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_INIT_ENERGY).getValue()));
        tmpDFWConfig.setEnergyRecoverySecond(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ENERGY_RECOVERY_SECOND).getValue()));
        // 商会配置
        List<Integer> additionDuration = StringUtils.stringToIntegerList(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_UNION_ADDITION_DURATION).getValue(), ";");
        tmpDFWConfig.setUnionMaxAddition(additionDuration.get(0));
        tmpDFWConfig.setUnionMinAddition(additionDuration.get(1));
        tmpDFWConfig.setZhuFuAddition(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ZHUFU_ADDITION).getValue()));
        tmpDFWConfig.setZhuFuNewsCount(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ZHUFU_RECORD_COUNT).getValue()));
        tmpDFWConfig.setZaoYaoAddition(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ZAOYAO_ADDITION).getValue()));
        tmpDFWConfig.setZaoYaoNewsCount(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ZAOYAO_RECORD_COUNT).getValue()));
        tmpDFWConfig.setUnionAdditionRecoverySecond(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_UNION_ADDITION_RECOVERY_SECOND).getValue()));
        tmpDFWConfig.setUnionBeatBackTimes(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_UNION_BEAT_BACK_TIMES).getValue()));
        tmpDFWConfig.setZaoYaoNewsCount(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ZAOYAO_RECORD_COUNT).getValue()));
        tmpDFWConfig.setEffectiveNewsCount(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_UNION_EFFECTIVE_NEWS_COUNT).getValue()));
        tmpDFWConfig.setUnEffectiveNewsCount(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_UNION_UNEFFECTIVE_NEWS_COUNT).getValue()));
        tmpDFWConfig.setRandomCardId(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_RANDOM_CARD_ID).getValue()));
        // 战斗配置
        tmpDFWConfig.setBaseDamage(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_BATTLE_BASE_DAMAGE).getValue()));
        tmpDFWConfig.setFreeBattleTimes(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_BATTLE_FREE_TIMES).getValue()));
        tmpDFWConfig.setBattleCost(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_BATTLE_COST).getValue());

        String quickKillLimitStr = "100|1";
        if (paramConfigMap.containsKey(eDaFuWengParamType.MONOPOLY_QUICK_KILL_LIMIT)) {
            quickKillLimitStr = paramConfigMap.get(eDaFuWengParamType.MONOPOLY_QUICK_KILL_LIMIT).getValue();
        }
        if (StringUtils.isNullOrEmpty(quickKillLimitStr)) {
            quickKillLimitStr = "100|1";
        }
        tmpDFWConfig.setFastBattleYongBingCardLimit(StringUtils.stringToIntegerList(quickKillLimitStr,"\\|").get(0));
        tmpDFWConfig.setFastBattleZhuiBuCardLimit(StringUtils.stringToIntegerList(quickKillLimitStr,"\\|").get(1));
        // 卡片配置
        tmpDFWConfig.setCardIdList(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ALL_CARD_ID_LIST).getValue());
        List<Integer> cardIdList = StringUtils.stringToIntegerList(tmpDFWConfig.getCardIdList(), ";");
        Map<Integer, eDaFuWengCardType> cardTypeMap = new ConcurrentHashMap<>();
        int i = 0;
        cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.Gold);
        cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.YaoYan);
        cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.ZhuFu);
        cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.Energy);
        cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.LuZhang);
        tmpDFWConfig.setYongBingCardDamage(initYongBingCardDamage(tmpDFWConfig, cardIdList.get(i))); // 缓存下佣兵卡伤害
        cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.YongBing);
        cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.QingShen);
        cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.HuoWu);
        cardTypeMap.put(cardIdList.get(i++), eDaFuWengCardType.ZhuiBu);
        tmpDFWConfig.setCardConfigMap(cardTypeMap);
        // 人偶配置
        tmpDFWConfig.setDollIdList(StringUtils.stringToIntegerList(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ALL_DOLL_ID_LIST).getValue(), ";"));
        for (Integer dollId : tmpDFWConfig.getDollIdList()) {
            GoodsInfo goodsInfo = CommonMgr.getGoodsInfo(dollId);
            if (goodsInfo != null && goodsInfo.getParamList().get(0).compareTo(BigInteger.ZERO) == 0) {
                tmpDFWConfig.setDefaultDollId(dollId);
                break;
            }
        }
        //密道配置
        tmpDFWConfig.setSecretBigRewardNumWeight(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_SECRET_BIG_REWARD_NUM_WEIGHT).getValue());
        tmpDFWConfig.setSecretBigRewardPool(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_SECRET_BIG_REWARD_POOL).getValue());
        tmpDFWConfig.setSecretNormalRewardPool(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_SECRET_NORMAL_REWARD_POOL).getValue());
        tmpDFWConfig.setSecretReRollPr(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_SECRET_RE_ROLL_PR).getValue());

        // 用户打理所需金币
        tmpDFWConfig.setAutoEventUnlockGold(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_AUTO_EVENT_GOLD_SCORE).getValue());
        tmpDFWConfig.setTenRollUnlock(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_TEN_UNLOCK).getValue());
        // 体力恢复道具ID
        tmpDFWConfig.setEnergyItemId(Integer.valueOf(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_ENERGY_ITEM_ID).getValue()));
        // 展示的皮肤
        tmpDFWConfig.setSkinIdList(paramConfigMap.get(eDaFuWengParamType.MONOPOLY_SHOW_SKIN_ID_LIST).getValue());

        // 商会返利事件解析
        String rebateParam = paramConfigMap.get(eDaFuWengParamType.MONOPOLY_BUG_GIFTS_RETURN_REWARDS).getValue();
        List<String> rebateParamStringList = StringUtils.stringToStringList(rebateParam, "\\|");
        Map<Integer, DFWRebateConfig> rebateMap = new ConcurrentHashMap<>();
        for (String param : rebateParamStringList) {
            List<String> p = StringUtils.stringToStringList(param, "-");
            DFWRebateConfig dfwRebateConfig = new DFWRebateConfig();
            dfwRebateConfig.setTimes(Integer.valueOf(p.get(0)));
            dfwRebateConfig.setRewards(p.get(1));
            rebateMap.put(dfwRebateConfig.getTimes(), dfwRebateConfig);
        }
        tmpDFWConfig.setRebateConfigMap(rebateMap);

        dfwConfig = tmpDFWConfig;

        getLogger().info("reload DaFuWeng end");

        // 在线玩家下发配置和数据
        onlinePlayerSendConfig();
    }

    /**
     * 同步配置
     */
    public static void syncDFWConfig(GamePlayer player) {
        MonopolyProto.SyncMonopolyConfigRespMsg.Builder respMsg = DaFuWengPb.parseSyncMonopolyConfigRespMsg(dfwConfig, player);
        player.sendPacket(ClientProtocol.U_DA_FU_WENG_CONFIG, respMsg);
    }

    public static void syncDFWUserData(GamePlayer player) {
        synchronized (lockObject) {
            if (player == null || dfwConfig == null || !ActivityMgr.activityInShowTime(dfwConfig.getActivityInfo())) {
                return;
            }

            DFWUserData dfwUserData = DaFuWengMgr.getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId());

            AutoFixLogic.fixParam(dfwUserData);

            checkDollExpire(dfwUserData);
            MonopolyProto.GetUserDataRespMsg.Builder builder = MonopolyProto.GetUserDataRespMsg.newBuilder();
            builder.setRet(0);
            builder.setUserData(DaFuWengPb.getUserDataMsg(dfwUserData));
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_GET_USER_DATA, builder);
            if (!StringUtils.isNullOrEmpty(player.getUserInfo().getUnionUid())) {
                notifyUnionData(player);
                syncUnionMemberDoll(player, null);
            }else {
                notifyEmptyUnionData(Collections.singletonList(player.getUserId()),"");
            }
        }
    }

    /**
     * 是否是人偶道具
     */
    public static boolean isDollItem(int goodsId) {
        DFWConfig config = getDfwConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return config.getDollIdList().contains(goodsId);
        }
        return false;
    }

    /**
     * 添加人偶
     */
    public static void addDoll(GamePlayer player, int dollId, BigInteger count) {
        DFWConfig config = getDfwConfig();
        DFWUserData userData = getUserData(config.getActivityInfo().getActivityId(), player.getUserId());
        long now = System.currentTimeMillis();
        GoodsInfo goodsInfo = CommonMgr.getGoodsInfo(dollId);
        if (goodsInfo == null) {
            getLogger().error("DaFuWengMgr error on addDoll! GoodsInfo is null!");
            return;
        }
        long addTime;
        try {
            addTime = 1000L * goodsInfo.getParamList().get(0).intValue() * count.intValue();
        } catch (Exception e) {
            getLogger().error("DaFuWengMgr error on addDoll! GoodsInfo is null!");
            return;
        }
        List<DFWDollData> dollList = userData.getDollList();
        for (DFWDollData dollData : dollList) {
            // 有人偶
            if (dollData.getDollId() == dollId) {
                long expireTime = dollData.getExpireTime();
                if (expireTime < now) {
                    dollData.setExpireTime(now + addTime);
                } else {
                    dollData.setExpireTime(expireTime + addTime);
                }
                userData.setUpdateOption();
                return;
            }
        }
        // 没人偶
        DFWDollData dollData = new DFWDollData(dollId, now + addTime);
        dollList.add(dollData);
        userData.setUpdateOption();
    }

    /**
     * 通知商会数据
     *
     * @param player
     */
    public static void notifyUnionData(GamePlayer player) {
        String unionUid = player.getUserInfo().getUnionUid();
        if (!StringUtils.isNullOrEmpty(unionUid)) {
            CrossMonopolyProto.CrossDfwSyncUnionMsg.Builder builder = CrossMonopolyProto.CrossDfwSyncUnionMsg.newBuilder();
            builder.setActivityId(dfwConfig.getActivityInfo().getActivityId());
            builder.setUnionId(unionUid);
            player.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_DA_FU_WENG_GET_UNION_DATA, builder, dfwConfig.getActivityInfo().getActivityId());
        }
    }

    /**
     * 退出商会通知商会数据置零
     */
    public static void notifyEmptyUnionData(List<Long> userList, String unionId) {
        DFWConfig dfwConfig = getDfwConfig();
        if (dfwConfig == null || !ActivityMgr.activityInTime(dfwConfig.getActivityInfo())) {
            return;
        }
        if (userList != null) {
            for (Long userId : userList) {
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
                if (player != null) {
                    player.sendPacket(ClientProtocol.U_DA_FU_WENG_UNION_DATA, DaFuWengPb.getEmptyUnionDataMsg());
                }
            }
        }
        Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionId);
        if (memberMap != null) {
            for (Long userId : memberMap.keySet()) {
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
                if (player != null) {
                    syncDFWUserData(player);
                }
            }
        }
    }

    public static void unionMemberChange(List<Long> userList) {
        DFWConfig dfwConfig = getDfwConfig();
        if (dfwConfig != null && ActivityMgr.activityInTime(dfwConfig.getActivityInfo())) {
            for (Long userId : userList) {
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
                if (player != null) {
                    syncUnionMemberDoll(player, null);
                }
            }
        }
    }

    /**
     * 同步商会成员人偶数据
     *
     * @param player
     */
    public static void syncUnionMemberDoll(GamePlayer player, MonopolyProto.UnionMemberDollTemp.Builder sendPlayer) {
      /*  MonopolyProto.SyncUnionMemberDollRespMsg.Builder respMsg = MonopolyProto.SyncUnionMemberDollRespMsg.newBuilder();
        String unionUid = player.getUserInfo().getUnionUid();
        if (!StringUtils.isNullOrEmpty(unionUid)) {
            Map<Long, CrossUnionMember> unionMemberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
            for (UnionMember member : unionMemberMap.values()) {
                GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(member.getUserId());
                if (onlinePlayer != null) {
                    DFWUserData userData = getUserData(dfwConfig.getActivityInfo().getActivityId(), member.getUserId());
                    if (userData != null && userData.getUserId() != player.getUserId() && (sendPlayer == null || sendPlayer.getUserId() != userData.getUserId())) {
                        respMsg.addUnionMemberDoll(DaFuWengPb.parseUnionMemberDollTemp(userData, member.getUserBaseInfo()));
                    }
                }
            }
            if (sendPlayer != null) {
                respMsg.addUnionMemberDoll(sendPlayer);
            }
        }
        player.sendChannelPacket(ClientProtocol.U_DA_FU_WENG_SYNC_UNION_MEMBER_DOLL, respMsg);*/
        String unionUid = player.getUserInfo().getUnionUid();
        if (!StringUtils.isNullOrEmpty(unionUid)) {
            MonopolyProto.GetUnionDollMsg.Builder msg = MonopolyProto.GetUnionDollMsg.newBuilder();
            msg.setActivityId(dfwConfig.getActivityInfo().getActivityId());
            Map<Long, CrossUnionMember> unionMemberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
            for (Long userId : unionMemberMap.keySet()) {
                if (userId != player.getUserId()) {
                    msg.addUserId(userId);
                }
            }
            player.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_DA_FU_WENG_UNION_DOLL_MSG, msg, dfwConfig.getActivityInfo().getActivityId());
        }

    }

    /**
     * 领取返利奖励
     *
     * @param player
     */
    public static void getRebateReward(GamePlayer player, int times) {
        MonopolyProto.GetRebateRewardRespMsg.Builder builder = MonopolyProto.GetRebateRewardRespMsg.newBuilder();
        builder.setRet(0);

        DFWConfig config = getDfwConfig();
        if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_GET_REBATE_REWARD, builder);
            return;
        }

        DFWRebateConfig rebateConfig = config.getRebateConfigMap().get(times);
        if (rebateConfig == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_DFW_PARAM_ERROR);
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_GET_REBATE_REWARD, builder);
            return;
        }

        synchronized (lockObject) {
            String unionUid = player.getUserInfo().getUnionUid();
            if (StringUtils.isNullOrEmpty(unionUid)) {
                builder.setRet(GameErrorCode.E_UNION_NO_JOIN_UNION);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_GET_REBATE_REWARD, builder);
                return;
            }

            DFWUserData dfwUserData = getUserData(config.getActivityInfo().getActivityId(), player.getUserId());
            if (dfwUserData.getRebateRewardRecord().contains(times)) {
                // 奖励已领取
                builder.setRet(GameErrorCode.E_ACTIVITY_DFW_HAS_GET_REWARD);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_GET_REBATE_REWARD, builder);
                return;
            }

            CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
            int crossServerCount = CrossUnionServerGroupMgr.getGroupServerCountByServerId(unionInfo.getServerId());
            int unionMaxMemberCount = UnionConfigMgr.getMaxMemberCount(unionInfo.getExperience(), unionInfo.isCross(), crossServerCount);

            //去跨服
            CrossMonopolyProto.CrossDfwUnionRebateReqMsg.Builder reqMsg = CrossMonopolyProto.CrossDfwUnionRebateReqMsg.newBuilder();
            reqMsg.setActivityId(dfwConfig.getActivityInfo().getActivityId());
            reqMsg.setUnionId(unionUid);
            reqMsg.setTimes(times);
            reqMsg.setMemberCount(unionMaxMemberCount);
            player.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_DA_FU_WENG_GET_UNION_REBATE_REWARD, reqMsg, dfwConfig.getActivityInfo().getActivityId());
        }
    }


    /**
     * 是否能购买现金礼包
     *
     * @param player
     * @param mallId
     * @return
     */
    public static boolean canBuyMallSucceed(GamePlayer player, int mallId) {
        DFWConfig config = getDfwConfig();
        if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
            return false;
        }
        synchronized (lockObject) {
            DFWUserData dfwUserData = DaFuWengMgr.getUserData(config.getActivityInfo().getActivityId(), player.getUserId());
            if (dfwUserData == null) {
                return false;
            }
            for (DfwPackageData data : dfwUserData.getPackageList()) {
                MallInfo mallInfo = NormalActivityMgr.getRMBActivityMallInfoByShopTypeAndExtendParam(config.getActivityInfo().getActivityId(), eShopType.DaFuWengMoneyMall.getValue(), data.getMallId());
                if (mallInfo == null) {
                    continue;
                }
                if (mallInfo.getMallId() == mallId) {
                    if (data.getNum() > 0) {
                        return true;
                    }
                }
            }
            DFWEvent dfwEvent = dfwConfig.getDfwEventMap().get(dfwUserData.getEventId());
            if (dfwEvent != null && dfwEvent.getEventType() == eDaFuWengEventType.Package) {
                // 是礼包事件
                MallInfo mallInfo = NormalActivityMgr.getRMBActivityMallInfoByShopTypeAndExtendParam(config.getActivityInfo().getActivityId(), eShopType.DaFuWengMoneyMall.getValue(), dfwEvent.getParamList().get(1));
                if (mallInfo.getMallId() == mallId) {
                    List<Integer> reTimesList = StringUtils.stringToIntegerList(dfwUserData.getExpandParam(), ",");
                    if (reTimesList.get(1) > 0) {
                        return true;
                    }
                }
            }

            if (dfwUserData.getMoneyMallList().contains(mallId)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否能购买现金礼包
     *
     * @param player
     * @param mallId
     * @return
     */
    public static boolean canPreCharge(GamePlayer player, int mallId) {
        DFWConfig config = getDfwConfig();
        if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
            return false;
        }

        synchronized (lockObject) {
            DFWUserData dfwUserData = DaFuWengMgr.getUserData(config.getActivityInfo().getActivityId(), player.getUserId());
            if (dfwUserData == null) {
                return false;
            }
            //只有礼包事件的时候允许预下单
            for (DfwPackageData data : dfwUserData.getPackageList()) {
                MallInfo mallInfo = NormalActivityMgr.getRMBActivityMallInfoByShopTypeAndExtendParam(config.getActivityInfo().getActivityId(), eShopType.DaFuWengMoneyMall.getValue(), data.getMallId());
                if (mallInfo == null) {
                   continue;
                }
                if (mallInfo.getMallId() == mallId && data.getNum() > 0) {
                    return true;
                }
            }
                /*if (mallInfo.getMallId() == mallId) {
                    List<Integer> reTimesList = StringUtils.stringToIntegerList(dfwUserData.getExpandParam(), ",");
                    if (reTimesList.get(1) > 0) {
                        return true;
                    }
                }*/
        }
        return false;
    }

    /**
     * 购买现金礼包
     *
     * @param player
     * @param mallId
     * @return
     */
    public static void buyMall(GamePlayer player, int mallId) {
        DFWConfig config = getDfwConfig();
        if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
            return;
        }

        synchronized (lockObject) {
            DFWUserData dfwUserData = DaFuWengMgr.getUserData(config.getActivityInfo().getActivityId(), player.getUserId());
            if (dfwUserData == null) {
                return;
            }

            DFWEvent dfwEvent = dfwConfig.getDfwEventMap().get(dfwUserData.getEventId());
            if (dfwEvent != null && dfwEvent.getEventType() == eDaFuWengEventType.Package) {
                // 是礼包事件
                MallInfo mallInfo = NormalActivityMgr.getRMBActivityMallInfoByShopTypeAndExtendParam(config.getActivityInfo().getActivityId(), eShopType.DaFuWengMoneyMall.getValue(), dfwEvent.getParamList().get(1));
                if (mallInfo.getMallId() == mallId) {
                    List<Integer> reTimesList = StringUtils.stringToIntegerList(dfwUserData.getExpandParam(), ",");
                    if (reTimesList.get(1) > 0) {
                        reTimesList.set(1, 0);
                        dfwUserData.setExpandParam(StringUtils.listToString(reTimesList, ","));
                        addUnionBuyTimes(player, config.getActivityInfo().getActivityId());
                        dfwUserData.reducePackage(dfwEvent.getParamList().get(1),eShopType.DaFuWengMoneyMall.getValue());
                        syncDFWUserData(player);
                        return;
                    }
                }
            }

            for (DfwPackageData data : dfwUserData.getPackageList()) {
                MallInfo mallInfo = NormalActivityMgr.getRMBActivityMallInfoByShopTypeAndExtendParam(config.getActivityInfo().getActivityId(), eShopType.DaFuWengMoneyMall.getValue(), data.getMallId());
                if (mallInfo == null) {
                    continue;
                }
                if (mallInfo.getMallId() == mallId) {
                    addUnionBuyTimes(player, config.getActivityInfo().getActivityId());
                    dfwUserData.reducePackage(data.getMallId(),eShopType.DaFuWengMoneyMall.getValue());
                    syncDFWUserData(player);
                }
            }

            // 延迟到账在列表内
          /*  if (dfwUserData.getMoneyMallList().contains(mallId)) {
                dfwUserData.getMoneyMallList().remove(Integer.valueOf(mallId));
                dfwUserData.setUpdateOption();

            }*/
        }

    }

    public static void addUnionBuyTimes(GamePlayer player, int activityId) {
        String unionUid = player.getModule(PlayerModule.class).getUserInfo().getUnionUid();
        if (!StringUtils.isNullOrEmpty(unionUid)) {
            CrossMonopolyProto.CrossDfwUnionAddBuyTimesReqMsg.Builder reqMsg = CrossMonopolyProto.CrossDfwUnionAddBuyTimesReqMsg.newBuilder();
            reqMsg.setActivityId(activityId);
            reqMsg.setUnionId(unionUid);
            reqMsg.setPlayerInfo(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId())));
            player.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_DA_FU_WENG_ADD_UNION_BUY_TIMES, reqMsg, activityId);
        }
        syncDFWUserData(player);
    }

    /**
     * 获取商会返利
     *
     * @param player
     * @param times
     */
    public static void getUnionRebate(GamePlayer player, int times) {
        MonopolyProto.GetRebateRewardRespMsg.Builder builder = MonopolyProto.GetRebateRewardRespMsg.newBuilder();
        builder.setRet(0);
        DFWConfig config = getDfwConfig();
        if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
            return;
        }

        DFWRebateConfig rebateConfig = config.getRebateConfigMap().get(times);
        if (rebateConfig == null) {
            builder.setRet(GameErrorCode.E_ACTIVITY_DFW_PARAM_ERROR);
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_GET_REBATE_REWARD, builder);
            return;
        }
        synchronized (lockObject) {
            String unionUid = player.getUserInfo().getUnionUid();
            if (StringUtils.isNullOrEmpty(unionUid)) {
                builder.setRet(GameErrorCode.E_UNION_NO_JOIN_UNION);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_GET_REBATE_REWARD, builder);
                return;
            }

            DFWUserData dfwUserData = getUserData(config.getActivityInfo().getActivityId(), player.getUserId());
            if (dfwUserData.getRebateRewardRecord().contains(times)) {
                // 奖励已领取
                builder.setRet(GameErrorCode.E_ACTIVITY_DFW_HAS_GET_REWARD);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_GET_REBATE_REWARD, builder);
                return;
            }
            // 增加个人领奖记录
            dfwUserData.getRebateRewardRecord().add(times);
            dfwUserData.setUpdateOption();
            player.getModule(CurrencyModule.class).addCurrency(PropertyHelper.parseStringToProperty(rebateConfig.getRewards()), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengGetRebateReward);
            syncDFWUserData(player);
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_GET_REBATE_REWARD, builder);
            AutoLogMgr.add(new LogDFWRebateReward(config.getActivityInfo().getActivityId(), player.getUserId(),
                    unionUid, times, new Date()));
        }
    }


    /**
     * 购买元宝礼包
     *
     * @param player
     */
    public static void buyPackage(GamePlayer player) {
        DFWConfig config = getDfwConfig();
        MonopolyProto.BuyPackageRespMsg.Builder builder = MonopolyProto.BuyPackageRespMsg.newBuilder();
        builder.setRet(0);
        if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_BUY_PACKAGE, builder);
            return;
        }

        synchronized (lockObject) {
            DFWUserData dfwUserData = DaFuWengMgr.getUserData(config.getActivityInfo().getActivityId(), player.getUserId());
            if (dfwUserData != null) {
                if (dfwUserData.getEventId() > 0 && !dfwUserData.isComplete()) {
                    DFWEvent dfwEvent = dfwConfig.getDfwEventMap().get(dfwUserData.getEventId());
                    if (dfwEvent.getEventType() == eDaFuWengEventType.Package) {
                        List<Integer> reTimesList = StringUtils.stringToIntegerList(dfwUserData.getExpandParam(), ",");
                        if (reTimesList.get(0) > 0) {
                            // 有剩余购买次数
                            MallInfo mallInfo = NormalActivityMgr.getRMBActivityMallInfoByShopTypeAndExtendParam(config.getActivityInfo().getActivityId(), eShopType.DaFuWengGoldMall.getValue(), dfwEvent.getParamList().get(0));
                            if (mallInfo.getActivityId() == config.getActivityInfo().getActivityId() && mallInfo.getShopType() == eShopType.DaFuWengGoldMall.getValue()) {
                                // 活动id及活动类型均要吻合才可购买
                                CurrencyModule currencyModule = player.getModule(CurrencyModule.class);
                                if (currencyModule.removeCurrency(PropertyHelper.parseStringToProperty(mallInfo.getPrice()), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengGoldPackageEvent)) {
                                    currencyModule.addCurrency(mallInfo.getReward(), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengGoldPackageEvent);
                                    reTimesList.set(0, reTimesList.get(0) - 1);
                                    dfwUserData.setExpandParam(StringUtils.listToString(reTimesList, ","));
                                    String priceStr = MallRechargeConfigMgr.getPriceStr(mallInfo);
                                    AutoLogMgr.add(new LogBuy(player.getUserId(), mallInfo.getMallId(), mallInfo.getReward(), 1,priceStr,
                                            mallInfo.getShopType(), mallInfo.getActivityType(), player.getUserInfo().getVipExp(), mallInfo.getMallMarkId()));
                                } else {
                                    // 道具不足
                                    builder.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
                                }
                            } else {
                                // 非该活动的商品id
                                builder.setRet(GameErrorCode.E_ACTIVITY_DFW_MALL_ID_ERROR);
                            }
                        } else {
                            // 无剩余购买次数
                            builder.setRet(GameErrorCode.E_ACTIVITY_DFW_NOT_BUY_TIMES);
                        }
                    } else {
                        // 不是礼包事件
                        builder.setRet(GameErrorCode.E_ACTIVITY_DFW_ERROR_EVENT);
                    }
                } else {
                    // 没有此事件
                    builder.setRet(GameErrorCode.E_ACTIVITY_DFW_EVENT_HAD_HANDLE);
                }
            } else {
                // 没有用户数据
                builder.setRet(GameErrorCode.E_ACTIVITY_DFW_PARAM_ERROR);
            }
            syncDFWUserData(player);
        }
        player.sendPacket(ClientProtocol.U_DA_FU_WENG_BUY_PACKAGE, builder);
    }


    public static void buyTenPackage(GamePlayer player, int mallId) {
        DFWConfig config = getDfwConfig();
        MonopolyProto.BuyPackageMallRespMsg.Builder builder = MonopolyProto.BuyPackageMallRespMsg.newBuilder();
        builder.setRet(0);
        if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
            builder.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_BUY_PACKAGE, builder);
            return;
        }

        synchronized (lockObject) {
            DFWUserData dfwUserData = DaFuWengMgr.getUserData(config.getActivityInfo().getActivityId(), player.getUserId());
            if (dfwUserData != null) {
                DfwPackageData packageData = dfwUserData.getPackageData(mallId);
                if (packageData != null && packageData.getNum() > 0) {
                    MallInfo mallInfo = NormalActivityMgr.getRMBActivityMallInfoByShopTypeAndExtendParam(config.getActivityInfo().getActivityId(), eShopType.DaFuWengGoldMall.getValue(), mallId);
                    if (mallInfo.getActivityId() == config.getActivityInfo().getActivityId() && mallInfo.getShopType() == eShopType.DaFuWengGoldMall.getValue()) {
                        // 活动id及活动类型均要吻合才可购买
                        CurrencyModule currencyModule = player.getModule(CurrencyModule.class);
                        if (currencyModule.removeCurrency(PropertyHelper.parseStringToProperty(mallInfo.getPrice()), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengGoldPackageEvent)) {
                            dfwUserData.reducePackage(mallId, packageData.getType());
                            currencyModule.addCurrency(mallInfo.getReward(), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengGoldPackageEvent);

                            String priceStr = MallRechargeConfigMgr.getPriceStr(mallInfo);
                            AutoLogMgr.add(new LogBuy(player.getUserId(), mallInfo.getMallId(), mallInfo.getReward(), 1, priceStr,
                                    mallInfo.getShopType(), mallInfo.getActivityType(), player.getUserInfo().getVipExp(), mallInfo.getMallMarkId()));
                        } else {
                            // 道具不足
                            builder.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
                        }
                    } else {
                        // 非该活动的商品id
                        builder.setRet(GameErrorCode.E_ACTIVITY_DFW_MALL_ID_ERROR);
                    }
                }else {
                    // 无剩余购买次数
                    builder.setRet(GameErrorCode.E_ACTIVITY_DFW_NOT_BUY_TIMES);
                }
            } else {
                // 没有用户数据
                builder.setRet(GameErrorCode.E_ACTIVITY_DFW_PARAM_ERROR);
            }
            syncDFWUserData(player);
        }
        player.sendPacket(ClientProtocol.U_DA_FU_WENG_BUY_MALL, builder);
    }


    public static boolean roll(GamePlayer player) {
        synchronized (lockObject) {
            MonopolyProto.UnionMemberMoveDataMsg.Builder moveData = initMoveData(player);
            LogDFWRoll rollLog = new LogDFWRoll();
            DFWConfig config = getDfwConfig();
            MonopolyProto.RollDiceRespMsg.Builder rollDiceRespMsg = MonopolyProto.RollDiceRespMsg.newBuilder();
            if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
                rollDiceRespMsg.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_ROLL, rollDiceRespMsg);
                return false;
            }
            //恢复体力
            recoveryPower(player);
            DFWUserData dfwUserData = DaFuWengMgr.getUserData(config.getActivityInfo().getActivityId(), player.getUserId());
            rollLog.setGoldScore(dfwUserData.getGoldScore());
            //体力是否足够
            if (dfwUserData.getEnergy() < config.getRollCostEnergy()) {
                rollDiceRespMsg.setRet(GameErrorCode.E_ACTIVITY_DFW_ENERGY_NO_ENOUGH);
                rollDiceRespMsg.setUserData(DaFuWengPb.getUserDataMsg(dfwUserData));
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_ROLL, rollDiceRespMsg);
                return false;
            }
            dfwUserData.setTenRoll(false);

            int randomNum = new Random().nextInt(6) + 1;

            rollDiceRespMsg.setDiceNum(randomNum);

            if (dfwUserData.getVehicleMoveTimes() > 0) {
                int vehicleAdd = getVehicleSkillAddition(config, dfwUserData.getVehicleId()).get(0);
                randomNum += vehicleAdd;
                rollLog.setVehicleAdd(vehicleAdd);
            }

            //路障
            LuZhangResult luZhangResult = LuZhangLogic.moveLuZhang(randomNum, dfwUserData);
            if (luZhangResult.isLuZhang()) {
                randomNum = luZhangResult.getStepNum();
            }

            // 神仙恢复体力数
            int godRecoveryEnergy = 0;

            if (!dfwUserData.isComplete() && dfwUserData.getEventId() > 0 && config.getDfwEventMap().get(dfwUserData.getEventId()).getEventType() == eDaFuWengEventType.Secret) {
                //密道
                int curIndex = Integer.parseInt(dfwUserData.getExpandParam());
                int overRoadIndex = dfwUserData.getUserSecretRoadList().size() - 1;
                if (curIndex + randomNum <= overRoadIndex) {
                    DFWUserSecretRoad dfwUserSecretRoad = dfwUserData.getUserSecretRoadList().get(curIndex + randomNum);
                    if (dfwUserSecretRoad.isBigReward()) {
                        Random random = new Random();
                        int reRollRandom = random.nextInt(1000) + 1;
                        int reRollWeight = Integer.parseInt(dfwConfig.getSecretReRollPr());
                        if (reRollWeight >= 1000) {
                            reRollWeight = reRollWeightDefault;
                        }
                        //被路障卡拦下 (摇出的色子点数会超出路障则不重摇)
                        if ((!luZhangResult.isLuZhang() || luZhangResult.isSmallPosition())) {
                            if (reRollRandom <= reRollWeight) {
                                //重新投掷
                                return roll(player);
                            }
                        }
                    }
                    // 神仙buff生效
                    int energyRec = getGodSkillAddition(config, dfwUserData.getDfwGodDataList()).get(2);
                    if (energyRec > 0) {
                        dfwUserData.setEnergy(dfwUserData.getEnergy() + energyRec);
                        godRecoveryEnergy = energyRec;
                    }
                    //扣除体力
                    removeEnergy(dfwUserData);
                    //触发后移除路障
                    LuZhangLogic.removeLuZhang(luZhangResult, dfwUserData);
                    //密道内移动记录
                    for (int i = curIndex + 1; i <= curIndex + randomNum; i++) {
                        MonopolyProto.MovePositionMsg.Builder movePositionBuilder = MonopolyProto.MovePositionMsg.newBuilder();
                        movePositionBuilder.setPositionIndex(i);
                        if (i == curIndex + randomNum) {
                            movePositionBuilder.setSecretRoadReward(dfwUserSecretRoad.getReward());
                        }
                        rollDiceRespMsg.addMovePositionList(movePositionBuilder);
                    }
                    //获得奖励
                    player.getModule(CurrencyModule.class).addCurrency(PropertyHelper.parseStringToProperty(dfwUserSecretRoad.getReward()),
                            eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengSecretRoad);
                    dfwUserData.getUserSecretRoadList().get(curIndex + randomNum).setGetReward(true);
                    dfwUserData.setExpandParam(String.valueOf(curIndex + randomNum));
                    // 聊天推送下获得大奖
                    if (dfwUserSecretRoad.isBigReward()) {
                        WorldMessageProto.WorldMessageTempMsg.Builder msg = WorldMessagePb.parseWorldMessageTempMsg(player.getUserInfo(), eMessageType.DaFuWeng.getValue(), eChatContentType.Common.getContentType(), dfwUserSecretRoad.getReward(), System.currentTimeMillis(), config.getActivityInfo().getActivityId(), null);
                        WorldMessageMgr.sendCrossActivityChat(msg);
                    }
                    rollDiceRespMsg.setRet(0);
                    rollDiceRespMsg.setUserData(DaFuWengPb.getUserDataMsg(dfwUserData));
                    rollDiceRespMsg.setEnergyRecovery(godRecoveryEnergy);
                    player.sendPacket(ClientProtocol.U_DA_FU_WENG_ROLL, rollDiceRespMsg);
                    overMoveData(player, moveData, rollDiceRespMsg.getMovePositionListCount());
                    addRollLog(rollLog, rollDiceRespMsg, player);
                    return true;
                } else {
                    //密道内移动记录
                    for (int i = curIndex + 1; i <= overRoadIndex; i++) {
                        MonopolyProto.MovePositionMsg.Builder movePositionBuilder = MonopolyProto.MovePositionMsg.newBuilder();
                        movePositionBuilder.setPositionIndex(i);
                        rollDiceRespMsg.addMovePositionList(movePositionBuilder);
                    }
                    int linkPosition = config.getDfwEventMap().get(dfwUserData.getEventId()).getParamList().get(1);
                    dfwUserData.setComplete(true);
                    dfwUserData.setExpandParam("");
                    //清空密道数据
                    dfwUserData.setUserSecretRoadList(new ArrayList<>());
                    //出口位置
                    dfwUserData.setPositionIndex(linkPosition - 1);
                    //剩余步数 接着往下走
                    randomNum = randomNum - (overRoadIndex - curIndex);
                }
            }

            if (dfwUserData.isComplete()) {
                // 神仙buff生效
                int energyRec = getGodSkillAddition(config, dfwUserData.getDfwGodDataList()).get(2);
                if (energyRec > 0) {
                    dfwUserData.setEnergy(dfwUserData.getEnergy() + energyRec);
                    godRecoveryEnergy = energyRec;

                }
                //扣除体力
                removeEnergy(dfwUserData);
                //触发后移除路障
                LuZhangLogic.removeLuZhang(luZhangResult, dfwUserData);
                // 其他事件已完成的情况下才能摇色子
                int index = 0;
                for (int i = 1; i <= randomNum; i++) {

                    if (dfwUserData.getPositionIndex() + i >= DaFuWengMgr.StepsNum) {
                        // 超圈
                        index = dfwUserData.getPositionIndex() + i - DaFuWengMgr.StepsNum;
                    } else {
                        index = dfwUserData.getPositionIndex() + i;
                    }
                    MonopolyProto.MovePositionMsg.Builder movePositionBuilder = MonopolyProto.MovePositionMsg.newBuilder();
                    movePositionBuilder.setPositionIndex(index);

                    DFWBuildingConfig dfwBuildingConfig = config.getBuildingConfigByPosition(index);
                    if (dfwBuildingConfig != null) {
                        BaseDFWBuilding building = BaseDFWBuilding.getBuilding(config, eDaFuWengBuildingType.forValue(dfwBuildingConfig.getBuildingId()), player);
                        if (i == randomNum) {
                            building.reach();
                        } else {
                            // 经过事件
                            building.passRoad();
                        }
                        movePositionBuilder.addAllEventList(building.getEventResultList());
                    }
                    rollDiceRespMsg.addMovePositionList(movePositionBuilder);

                }

                MonopolyProto.MonopolyPlayerMsg.Builder builder = MonopolyProto.MonopolyPlayerMsg.newBuilder();
                builder.setUserId(player.getUserId());
                builder.setPlayer(PlayerPb.parsePlayerBaseTempMsg(player.getUserInfo()));
                dfwUserData.setPositionIndex(index);
                rollDiceRespMsg.setRet(0);
                rollDiceRespMsg.setUserData(DaFuWengPb.getUserDataMsg(dfwUserData));
                rollDiceRespMsg.setEnergyRecovery(godRecoveryEnergy);
                overMoveData(player, moveData, rollDiceRespMsg.getMovePositionListCount());
                addRollLog(rollLog, rollDiceRespMsg, player);

                if (dfwConfig.getDfwEventMap().get(dfwUserData.getEventId()) != null) {
                    if (eDaFuWengEventType.Boss == dfwConfig.getDfwEventMap().get(dfwUserData.getEventId()).getEventType()) {
                        dfwUserData.setFreeBattleTimes(config.getFreeBattleTimes());
                        bossEventPreHandle(player, dfwConfig, rollDiceRespMsg);
                        return false;
                    } else if (eDaFuWengEventType.ZaoYao == dfwConfig.getDfwEventMap().get(dfwUserData.getEventId()).getEventType()) {
                        dfwUserData.setPositionIndex(index);
                        zaoYaoEventPreHandle(player, dfwConfig, rollDiceRespMsg);
                        return false;
                    }
                }
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_ROLL, rollDiceRespMsg);
            } else {
                rollDiceRespMsg.setRet(GameErrorCode.E_ACTIVITY_DFW_EVENT_INCOMPLETE);
                rollDiceRespMsg.setUserData(DaFuWengPb.getUserDataMsg(dfwUserData));
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_ROLL, rollDiceRespMsg);
            }
            return true;
        }
    }

    public static void tenRoll(GamePlayer player) {
        int ret = 0;
        DFWUserData userData = getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId());
        String tenRollUnlock = dfwConfig.getTenRollUnlock();
        String[] split = tenRollUnlock.split(";");
        long needScore = Long.parseLong(split[0]);
        int needVipLv = Integer.parseInt(split[1]);
        if (userData == null || (userData.getGoldScore() < needScore && VipMgr.getVipLv(player.getUserInfo().getVipExp()) < needVipLv)) {
            ret = GameErrorCode.E_ACTIVITY_DFW_TEN_ROLL_LOCK;
            MonopolyProto.TenRollDiceRespMsg.Builder resp = MonopolyProto.TenRollDiceRespMsg.newBuilder();
            resp.setRet(ret);
            resp.setUserData(DaFuWengPb.getUserDataMsg(getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId())));
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_TEN_ROLL, resp);
            return;
        }
        userData.setTenRoll(true);
        DFWTenRollResult result = new DFWTenRollResult();
        for (int i = 0; i < 10; i++) {
            tenRealRoll(player, result);
            if (result.isNeedBreak()) {
                break;
            }
        }

        if (result.isZaoyao() || result.getBossNum() > 0) {
            MonopolyProto.DfwTenRollCrossReqMsg.Builder msg = MonopolyProto.DfwTenRollCrossReqMsg.newBuilder();
            msg.setActivityId(dfwConfig.getActivityInfo().getActivityId());
            msg.setUserId(player.getUserId());
            MonopolyProto.MonopolyPlayerMsg monopolyPlayerMsg = DaFuWengPb.parseMonopolyPlayerMsg(
                    player.getUserId(),
                    PlayerPb.parsePlayerBaseTempMsg(player.getUserInfo()).build());
            msg.setMonopolyPlayer(monopolyPlayerMsg);
            msg.setZaoyao(result.isZaoyao());
            int bossNum = result.getBossNum();
            for (int i = 0; i < bossNum; i++) {
                int damage = calTenDamage(userData, dfwConfig, player.getUserInfo().getUnionUid());
                MonopolyProto.DfwTenRollAttackBossMsg.Builder bossMsg = MonopolyProto.DfwTenRollAttackBossMsg.newBuilder();
                bossMsg.setDamage(damage);
                msg.addBossDamageMsg(bossMsg);
            }
            msg.setReward(PropertyHelper.parsePropertyToString(result.getReward()));
            msg.setAddPower(result.getEnergyRecovery());
            msg.setRollTimes(result.getRollTimes());
            player.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_DA_FU_WENG_TEN_ROLL_CROSS, msg, dfwConfig.getActivityInfo().getActivityId());
        }else {
            MonopolyProto.TenRollDiceRespMsg.Builder resp = MonopolyProto.TenRollDiceRespMsg.newBuilder();
            resp.setRet(ret);
            if (!result.getReward().isNothing()) {
                resp.setReward(PropertyHelper.parsePropertyToString(result.getReward()));
            }
            resp.setEnergyRecovery(result.getEnergyRecovery());
            resp.setUserData(DaFuWengPb.getUserDataMsg(getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId())));
            resp.setRollTimes(result.getRollTimes());
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_TEN_ROLL, resp);
        }

    }

    private static void tenRealRoll(GamePlayer player, DFWTenRollResult result) {
        synchronized (lockObject) {
            MonopolyProto.UnionMemberMoveDataMsg.Builder moveData = initMoveData(player);
            LogDFWRoll rollLog = new LogDFWRoll();
            DFWConfig config = getDfwConfig();
            MonopolyProto.RollDiceRespMsg.Builder rollDiceRespMsg = MonopolyProto.RollDiceRespMsg.newBuilder();
            if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
                result.setNeedBreak(true);
                return;
            }
            //恢复体力
            recoveryPower(player);
            DFWUserData dfwUserData = DaFuWengMgr.getUserData(config.getActivityInfo().getActivityId(), player.getUserId());
            rollLog.setGoldScore(dfwUserData.getGoldScore());
            //体力是否足够
            if (dfwUserData.getEnergy() < config.getRollCostEnergy()) {
                result.setNeedBreak(true);
                return;
            }

            int randomNum = new Random().nextInt(6) + 1;
            rollDiceRespMsg.setDiceNum(randomNum);
            if (dfwUserData.getVehicleMoveTimes() > 0) {
                int vehicleAdd = getVehicleSkillAddition(config, dfwUserData.getVehicleId()).get(0);
                randomNum += vehicleAdd;
                rollLog.setVehicleAdd(vehicleAdd);
            }

            //路障
            LuZhangResult luZhangResult = LuZhangLogic.moveLuZhang(randomNum, dfwUserData);

            if (luZhangResult.isLuZhang()) {
                randomNum = luZhangResult.getStepNum();
            }

            // 神仙恢复体力数
            int godRecoveryEnergy = 0;

            if (!dfwUserData.isComplete() && dfwUserData.getEventId() > 0 && config.getDfwEventMap().get(dfwUserData.getEventId()).getEventType() == eDaFuWengEventType.Secret) {
                //密道
                int curIndex = Integer.parseInt(dfwUserData.getExpandParam());
                int overRoadIndex = dfwUserData.getUserSecretRoadList().size() - 1;
                if (curIndex + randomNum <= overRoadIndex) {
                    DFWUserSecretRoad dfwUserSecretRoad = dfwUserData.getUserSecretRoadList().get(curIndex + randomNum);
                    if (dfwUserSecretRoad.isBigReward()) {
                        Random random = new Random();
                        int reRollRandom = random.nextInt(1000) + 1;
                        int reRollWeight = Integer.parseInt(dfwConfig.getSecretReRollPr());
                        if (reRollWeight >= 1000) {
                            reRollWeight = reRollWeightDefault;
                        }
                        //被路障卡拦下 (摇出的色子点数会超出路障则不重摇)
                        if ((!luZhangResult.isLuZhang() || luZhangResult.isSmallPosition())) {
                            if (reRollRandom <= reRollWeight) {
                                //重新投掷
                                 tenRealRoll(player, result);
                                 return;
                            }
                        }
                    }
                    if (luZhangResult.isLuZhang()) {
                        result.setNeedBreak(true);
                    }
                    // 神仙buff生效
                    int energyRec = getGodSkillAddition(config, dfwUserData.getDfwGodDataList()).get(2);
                    if (energyRec > 0) {
                        dfwUserData.setEnergy(dfwUserData.getEnergy() + energyRec);
                        godRecoveryEnergy = energyRec;
                        result.addPower(godRecoveryEnergy);
                    }
                    //扣除体力
                    removeEnergy(dfwUserData);
                    //触发后移除路障
                    LuZhangLogic.removeLuZhang(luZhangResult, dfwUserData);
                    //密道内移动记录
                    for (int i = curIndex + 1; i <= curIndex + randomNum; i++) {
                        MonopolyProto.MovePositionMsg.Builder movePositionBuilder = MonopolyProto.MovePositionMsg.newBuilder();
                        movePositionBuilder.setPositionIndex(i);
                        if (i == curIndex + randomNum) {
                            movePositionBuilder.setSecretRoadReward(dfwUserSecretRoad.getReward());
                        }
                        rollDiceRespMsg.addMovePositionList(movePositionBuilder);
                    }
                    //获得奖励
                    player.getModule(CurrencyModule.class).addCurrency(PropertyHelper.parseStringToProperty(dfwUserSecretRoad.getReward()),
                            eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengSecretRoad);
                    dfwUserData.getUserSecretRoadList().get(curIndex + randomNum).setGetReward(true);
                    dfwUserData.setExpandParam(String.valueOf(curIndex + randomNum));
                    // 聊天推送下获得大奖
                    if (dfwUserSecretRoad.isBigReward()) {
                        WorldMessageProto.WorldMessageTempMsg.Builder msg = WorldMessagePb.parseWorldMessageTempMsg(player.getUserInfo(), eMessageType.DaFuWeng.getValue(), eChatContentType.Common.getContentType(), dfwUserSecretRoad.getReward(), System.currentTimeMillis(), config.getActivityInfo().getActivityId(), null);
                        WorldMessageMgr.sendCrossActivityChat(msg);
                    }
                    rollDiceRespMsg.setRet(0);
                    rollDiceRespMsg.setUserData(DaFuWengPb.getUserDataMsg(dfwUserData));
                    rollDiceRespMsg.setEnergyRecovery(godRecoveryEnergy);
                    overMoveData(player, moveData, rollDiceRespMsg.getMovePositionListCount());
                    addRollLog(rollLog, rollDiceRespMsg, player);
                    addResultReward(result, rollDiceRespMsg);
                    result.addRollTimes();
                    return;
                } else {
                    //密道内移动记录
                    for (int i = curIndex + 1; i <= overRoadIndex; i++) {
                        MonopolyProto.MovePositionMsg.Builder movePositionBuilder = MonopolyProto.MovePositionMsg.newBuilder();
                        movePositionBuilder.setPositionIndex(i);
                        rollDiceRespMsg.addMovePositionList(movePositionBuilder);
                    }
                    int linkPosition = config.getDfwEventMap().get(dfwUserData.getEventId()).getParamList().get(1);
                    dfwUserData.setComplete(true);
                    dfwUserData.setExpandParam("");
                    //清空密道数据
                    dfwUserData.setUserSecretRoadList(new ArrayList<>());
                    //出口位置
                    dfwUserData.setPositionIndex(linkPosition - 1);
                    //剩余步数 接着往下走
                    randomNum = randomNum - (overRoadIndex - curIndex);
                }
            }

            if (dfwUserData.isComplete()) {
                if (luZhangResult.isLuZhang()) {
                    result.setNeedBreak(true);
                }
                // 神仙buff生效
                int energyRec = getGodSkillAddition(config, dfwUserData.getDfwGodDataList()).get(2);
                if (energyRec > 0) {
                    dfwUserData.setEnergy(dfwUserData.getEnergy() + energyRec);
                    godRecoveryEnergy = energyRec;
                }
                //扣除体力
                removeEnergy(dfwUserData);
                //触发后移除路障
                LuZhangLogic.removeLuZhang(luZhangResult, dfwUserData);
                // 其他事件已完成的情况下才能摇色子
                int index = 0;
                for (int i = 1; i <= randomNum; i++) {

                    if (dfwUserData.getPositionIndex() + i >= DaFuWengMgr.StepsNum) {
                        // 超圈
                        index = dfwUserData.getPositionIndex() + i - DaFuWengMgr.StepsNum;
                    } else {
                        index = dfwUserData.getPositionIndex() + i;
                    }
                    MonopolyProto.MovePositionMsg.Builder movePositionBuilder = MonopolyProto.MovePositionMsg.newBuilder();
                    movePositionBuilder.setPositionIndex(index);

                    DFWBuildingConfig dfwBuildingConfig = config.getBuildingConfigByPosition(index);
                    if (dfwBuildingConfig != null) {
                        BaseDFWBuilding building = BaseDFWBuilding.getBuilding(config, eDaFuWengBuildingType.forValue(dfwBuildingConfig.getBuildingId()), player);
                        if (i == randomNum) {
                            building.reach();
                        } else {
                            // 经过事件
                            building.passRoad();
                        }
                        movePositionBuilder.addAllEventList(building.getEventResultList());
                    }
                    rollDiceRespMsg.addMovePositionList(movePositionBuilder);
                }

                MonopolyProto.MonopolyPlayerMsg.Builder builder = MonopolyProto.MonopolyPlayerMsg.newBuilder();
                builder.setUserId(player.getUserId());
                builder.setPlayer(PlayerPb.parsePlayerBaseTempMsg(player.getUserInfo()));
                dfwUserData.setPositionIndex(index);
                rollDiceRespMsg.setRet(0);
                rollDiceRespMsg.setUserData(DaFuWengPb.getUserDataMsg(dfwUserData));
                rollDiceRespMsg.setEnergyRecovery(godRecoveryEnergy);
                overMoveData(player, moveData, rollDiceRespMsg.getMovePositionListCount());
                addRollLog(rollLog, rollDiceRespMsg, player);
                addResultReward(result, rollDiceRespMsg);
                if (dfwConfig.getDfwEventMap().get(dfwUserData.getEventId()) != null) {
                    if (eDaFuWengEventType.Boss == dfwConfig.getDfwEventMap().get(dfwUserData.getEventId()).getEventType()) {
                        dfwUserData.setFreeBattleTimes(0);
                        dfwUserData.setComplete(true);
                        result.addBossTimes();
                        dfwUserData.setEventId(getEmptyEventId(dfwConfig));
                    } else if (eDaFuWengEventType.ZaoYao == dfwConfig.getDfwEventMap().get(dfwUserData.getEventId()).getEventType()) {
                        dfwUserData.setPositionIndex(index);
                     //   zaoYaoEventPreHandle(player, dfwConfig, rollDiceRespMsg);
                        result.setZaoyao(true);
                        result.setNeedBreak(true);
                    } else if (eDaFuWengEventType.Trade == dfwConfig.getDfwEventMap().get(dfwUserData.getEventId()).getEventType()) {
                        autoTradeEvent(player, result);
                    } else if (eDaFuWengEventType.Cal == dfwConfig.getDfwEventMap().get(dfwUserData.getEventId()).getEventType()) {
                        autoDivinationEvent(player, result);
                    } else if (eDaFuWengEventType.Package == dfwConfig.getDfwEventMap().get(dfwUserData.getEventId()).getEventType()) {
                        dfwUserData.setComplete(true);
                        dfwUserData.setEventId(getEmptyEventId(dfwConfig));
                    } else if (eDaFuWengEventType.Secret == dfwConfig.getDfwEventMap().get(dfwUserData.getEventId()).getEventType() && !dfwUserData.isComplete()) {
                        result.setNeedBreak(true);
                    }
                }
            } else {
                result.setNeedBreak(true);
            }
            result.addRollTimes();
        }
    }

    private static void addResultReward(DFWTenRollResult result, MonopolyProto.RollDiceRespMsg.Builder rollDiceRespMsg) {
        for (MonopolyProto.MovePositionMsg.Builder movePosition : rollDiceRespMsg.getMovePositionListBuilderList()) {
            if (movePosition.hasSecretRoadReward()) {
               result.addProperty(PropertyHelper.parseStringToProperty(movePosition.getSecretRoadReward()));
            } else {
                List<MonopolyProto.EventResultMsg> eventList = movePosition.getEventListList();
                for (MonopolyProto.EventResultMsg eventResultMsg : eventList) {
                    if (eventResultMsg.getEventId() != 0 && !eventResultMsg.getCollectLimit()) {
                        result.addProperty(PropertyHelper.parseStringToProperty(eventResultMsg.getReward()));
                    }
                }
            }
        }
    }

    public static void autoDivinationEvent(GamePlayer player, DFWTenRollResult result) {
        synchronized (lockObject) {
            if (dfwConfig == null || !ActivityMgr.activityInTime(dfwConfig.getActivityInfo())) {
                return;
            }
            DFWUserData userData = DaFuWengMgr.getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId());
            if (userData.isComplete()) {
                return;
            }
            int eventId = userData.getEventId();
            Map<Integer, DFWEvent> dfwEventMap = dfwConfig.getDfwEventMap();
            DFWEvent event = dfwEventMap.get(eventId);
            if (event == null) {
                return;
            }
            if (event.getEventType() != eDaFuWengEventType.Cal) {
                return;
            }

            // 加奖励
            String rewards = event.getRewards();
            player.getModule(CurrencyModule.class).addCurrency(PropertyHelper.parseStringToProperty(rewards), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengDivinationEvent);
            result.addProperty(PropertyHelper.parseStringToProperty(rewards));
            // 修改状态
            userData.setComplete(true);
            userData.setEventId(getEmptyEventId(dfwConfig));

        }
    }

    public static void autoTradeEvent(GamePlayer player, DFWTenRollResult result) {
        synchronized (lockObject) {
            DFWConfig config = DaFuWengMgr.getDfwConfig();
            if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
                return;
            }
            DFWUserData userData = DaFuWengMgr.getUserData(config.getActivityInfo().getActivityId(), player.getUserId());
            if (userData.isComplete()) {
                return;
            }
            int eventId = userData.getEventId();
            Map<Integer, DFWEvent> dfwEventMap = config.getDfwEventMap();
            DFWEvent event = dfwEventMap.get(eventId);
            if (event == null) {
                return;
            }
            if (event.getEventType() != eDaFuWengEventType.Trade) {
                return;
            }

            Integer goodsId = event.getParamList().get(0);
            Integer goodsCount = event.getParamList().get(1);
            Property property = new Property(goodsId, BigInteger.valueOf(goodsCount));
            CurrencyModule currencyModule = player.getModule(CurrencyModule.class);
            if (!currencyModule.currencyIsEnough(property)) {
                userData.setComplete(true);
                return;
            }
            // 扣道具，加奖励
            currencyModule.removeCurrency(property, eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengTradeEvent);
            String rewardStr = event.getRewards();
            currencyModule.addCurrency(PropertyHelper.parseStringToProperty(rewardStr), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengTradeEvent);
            result.addProperty(PropertyHelper.parseStringToProperty(rewardStr));
            // 改状态
            userData.setComplete(true);
            userData.setEventId(getEmptyEventId(dfwConfig));
        }
    }


    public static void addRollLog(LogDFWRoll log, MonopolyProto.RollDiceRespMsg.Builder rollDiceRespMsg, GamePlayer player) {
        try {
            for (int i = 0; i < rollDiceRespMsg.getMovePositionListCount(); i++) {
                LogDFWRoll newLog = new LogDFWRoll();
                newLog.setActivityId(dfwConfig.getActivityInfo().getActivityId());
                newLog.setUserId(player.getUserId());
                newLog.setUnionUid(player.getUserInfo().getUnionUid());
                newLog.setDollId(rollDiceRespMsg.getUserData().getDollId());
                newLog.setDiceNum(rollDiceRespMsg.getDiceNum());
                newLog.setRealStepNum(rollDiceRespMsg.getMovePositionListCount());
                newLog.setGoldScore(log.getGoldScore());
                newLog.setVehicleAdd(log.getVehicleAdd());
                MonopolyProto.MovePositionMsg movePosition = rollDiceRespMsg.getMovePositionList(i);
                if (movePosition.hasSecretRoadReward()) {
                    newLog.setReward(movePosition.getSecretRoadReward());
                    newLog.setEventId(rollDiceRespMsg.getUserData().getEventId());
                } else {
                    List<MonopolyProto.EventResultMsg> eventList = movePosition.getEventListList();
                    for (MonopolyProto.EventResultMsg eventResultMsg : eventList) {
                        if (eventResultMsg.getEventId() != 0) {
                            if (eventResultMsg.getEventId() < 20001) {
                                newLog.setBaseReward(eventResultMsg.getReward());
                            } else {
                                newLog.setEventId(eventResultMsg.getEventId());
                                newLog.setReward(eventResultMsg.getReward());
                            }
                        }
                    }
                }
                newLog.setPositionIndex(movePosition.getPositionIndex());
                if (i == rollDiceRespMsg.getMovePositionListCount() - 1) {
                    newLog.setAction("到达");
                } else {
                    newLog.setAction("经过");
                }
                newLog.setTime(System.currentTimeMillis());
                AutoLogMgr.add(newLog);
            }
        } catch (Exception e) {
            getLogger().error("dfw activity add log error!");
        }
    }

    private static void overMoveData(GamePlayer player, MonopolyProto.UnionMemberMoveDataMsg.Builder moveData, int moveStep) {
        DFWUserData dfwUserData = DaFuWengMgr.getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId());
        moveData.setMoveStep(moveStep);
        if (isSecretRoadEvent(dfwUserData)) {
            moveData.setSecretOverPosition(Integer.parseInt(dfwUserData.getExpandParam()));
        }
        moveData.setNormalOverPosition(dfwUserData.getPositionIndex());
        MonopolyProto.UnionMemberDollTemp.Builder temp = MonopolyProto.UnionMemberDollTemp.newBuilder();
        temp.setMoveData(moveData);
        temp.setUserId(dfwUserData.getUserId());
        temp.setUserName(player.getUserInfo().getNickName());
        temp.setGoldScore(dfwUserData.getGoldScore());
        temp.setDollId(dfwUserData.getDollId());
        for (DFWGodData dfwGodData : dfwUserData.getDfwGodDataList()) {
            temp.addGodData(DaFuWengPb.parseGodData(dfwGodData));
        }
        temp.setVehicleId(dfwUserData.getVehicleId());
        temp.setSex(player.getUserInfo().getSex());
        uploadDollMsg(player, temp, true);
    }

    private static void uploadDollMsg(GamePlayer player,MonopolyProto.UnionMemberDollTemp.Builder builder,boolean isMove) {

        MonopolyProto.NotifyDollMoveMsg.Builder synMsg = MonopolyProto.NotifyDollMoveMsg.newBuilder();
        synMsg.setActivityId(dfwConfig.getActivityInfo().getActivityId());
        synMsg.setUnionId(player.getUserInfo().getUnionUid());
        synMsg.setDollMsg(builder);
        synMsg.setIsMove(isMove);
        player.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_DA_FU_WENG_UPLOAD_DOLL, synMsg, dfwConfig.getActivityInfo().getActivityId());
    }

    private static MonopolyProto.UnionMemberMoveDataMsg.Builder initMoveData(GamePlayer player) {
        MonopolyProto.UnionMemberMoveDataMsg.Builder moveData = MonopolyProto.UnionMemberMoveDataMsg.newBuilder();
        DFWUserData dfwUserData = DaFuWengMgr.getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId());
        if (isSecretRoadEvent(dfwUserData)) {
            moveData.setSecretBeginPosition(Integer.parseInt(dfwUserData.getExpandParam()));
        }
        moveData.setNormalBeginPosition(dfwUserData.getPositionIndex());
        return moveData;
    }

    private static void removeEnergy(DFWUserData dfwUserData) {
        // 扣坐骑次数
        if (dfwUserData.getVehicleMoveTimes() > 0) {
            dfwUserData.setVehicleMoveTimes(dfwUserData.getVehicleMoveTimes() - 1);
            if (dfwUserData.getVehicleMoveTimes() <= 0) {
                dfwUserData.setVehicleId(0);
            }
        }
        // 扣神次数
        Iterator<DFWGodData> dFWGodDataIterator = dfwUserData.getDfwGodDataList().iterator();
        while (dFWGodDataIterator.hasNext()) {
            DFWGodData dfwGodData = dFWGodDataIterator.next();
            dfwGodData.setGodMoveTimes(dfwGodData.getGodMoveTimes() - 1);
            if (dfwGodData.getGodMoveTimes() <= 0) {
                dFWGodDataIterator.remove();
            }
        }
        // 清空extendParam
        dfwUserData.setExpandParam("");

        // 扣体力
        boolean isBigThanMax = dfwUserData.getEnergy() >= dfwConfig.getMaxEnergy();
        dfwUserData.setEnergy(dfwUserData.getEnergy() - dfwConfig.getRollCostEnergy());
        if (dfwUserData.getEnergy() < dfwConfig.getMaxEnergy() && isBigThanMax) {
            dfwUserData.setLastRecoveryTime(System.currentTimeMillis());
        }
    }

    /**
     * 碰到boss事件预处理
     */
    public static void bossEventPreHandle(GamePlayer player, DFWConfig config, MonopolyProto.RollDiceRespMsg.Builder rollMsg) {
        // 发到跨服请求BossId
        MonopolyProto.CrossPreHandleBossEventReqMsg.Builder builder = MonopolyProto.CrossPreHandleBossEventReqMsg.newBuilder();
        builder.setActivityId(config.getActivityInfo().getActivityId());
        builder.setServerId(player.getUserInfo().getOriginalServerId());
        builder.setUserId(player.getUserId());
        builder.setRollMsg(rollMsg);
        builder.setUnionUid(player.getUserInfo().getUnionUid());
        player.sendUnionActivityGroupPacket(Protocol.C_CROSS_DA_FU_WENG_PRE_HANDLE_BOSS_EVENT, builder, config.getActivityInfo().getActivityId());
    }

    /**
     * 碰到造谣事件预处理
     */
    public static void zaoYaoEventPreHandle(GamePlayer player, DFWConfig config, MonopolyProto.RollDiceRespMsg.Builder rollMsg) {
        MonopolyProto.CrossPreHandleZaoYaoEventReqMsg.Builder builder = MonopolyProto.CrossPreHandleZaoYaoEventReqMsg.newBuilder();
        builder.setActivityId(config.getActivityInfo().getActivityId());
        builder.setServerId(player.getUserInfo().getOriginalServerId());
        builder.setUserId(player.getUserId());
        builder.setRollMsg(rollMsg);
        builder.setUnionUid(player.getUserInfo().getUnionUid());
        player.sendUnionActivityGroupPacket(Protocol.C_CROSS_DA_FU_WENG_PRE_HANDLE_ZAO_YAO_EVENT, builder, config.getActivityInfo().getActivityId());
    }

    /**
     * 算卦事件
     */
    public static void divinationEvent(GamePlayer player) {
        synchronized (lockObject) {
            if (dfwConfig == null || !ActivityMgr.activityInTime(dfwConfig.getActivityInfo())) {
                return;
            }
            DFWUserData userData = DaFuWengMgr.getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId());
            if (userData.isComplete()) {
                MonopolyProto.HandleDivinationEventRespMsg.Builder builder = MonopolyProto.HandleDivinationEventRespMsg.newBuilder();
                builder.setRet(GameErrorCode.E_ACTIVITY_DFW_EVENT_HAD_HANDLE);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_DIVINATION_EVENT, builder);
                return;
            }
            int eventId = userData.getEventId();
            Map<Integer, DFWEvent> dfwEventMap = dfwConfig.getDfwEventMap();
            DFWEvent event = dfwEventMap.get(eventId);
            if (event == null) {
                return;
            }
            if (event.getEventType() != eDaFuWengEventType.Cal) {
                MonopolyProto.HandleDivinationEventRespMsg.Builder builder = MonopolyProto.HandleDivinationEventRespMsg.newBuilder();
                builder.setRet(GameErrorCode.E_ACTIVITY_DFW_EVENT_TYPE_ERROR);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_DIVINATION_EVENT, builder);
                return;
            }

            // 加奖励
            String rewards = event.getRewards();
            player.getModule(CurrencyModule.class).addCurrency(PropertyHelper.parseStringToProperty(rewards), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengDivinationEvent);

            // 修改状态
            userData.setComplete(true);

            // 给他2个看的
            List<Integer> showEventList = new ArrayList<>();

            // 返回
            MonopolyProto.HandleDivinationEventRespMsg.Builder builder = MonopolyProto.HandleDivinationEventRespMsg.newBuilder();
            builder.setRet(0);
            builder.setEventId(eventId);
            builder.addAllShowEventList(showEventList);
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_DIVINATION_EVENT, builder);
        }
    }

    /**
     * 跨服返回的跳过boss事件
     */
    public static void crossBossSkipEvent(GamePlayer player, int activityId, int bossId, boolean canSkip) {
        synchronized (getLockObject()) {
            DFWConfig config = getDfwConfig();
            DFWUserData userData = getUserData(activityId, player.getUserId());
            DFWEvent event = config.getDfwEventMap().get(userData.getEventId());
            if (event.getEventType() == eDaFuWengEventType.Boss) {
                List<Integer> list = StringUtils.stringToIntegerList(userData.getExpandParam(), ";");
                if (list.get(0) == bossId) {

                    if (canSkip) {
                        userData.setComplete(true);
                        userData.setEventId(0);
                    }

                    MonopolyProto.SkipEventRespMsg.Builder builder = MonopolyProto.SkipEventRespMsg.newBuilder();
                    builder.setRet(canSkip ? 0 : GameErrorCode.E_ACTIVITY_DFW_EVENT_CAN_NOT_SKIP);
                    player.sendPacket(ClientProtocol.U_DA_FU_WENG_SKIP_EVENT, builder);
                }
            }
        }
    }

    public static void skipEvent(GamePlayer player) {
        synchronized (lockObject) {
            DFWConfig config = getDfwConfig();
            if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
                return;
            }
            DFWUserData userData = DaFuWengMgr.getUserData(config.getActivityInfo().getActivityId(), player.getUserId());
            if (userData.isComplete()) {
                MonopolyProto.SkipEventRespMsg.Builder builder = MonopolyProto.SkipEventRespMsg.newBuilder();
                builder.setRet(0);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_SKIP_EVENT, builder);
                return;
            }
            int eventId = userData.getEventId();
            Map<Integer, DFWEvent> dfwEventMap = config.getDfwEventMap();
            DFWEvent event = dfwEventMap.get(eventId);
            if (event == null) {
                return;
            }

            // 不可跳过的情况
            if (event.getEventType() == eDaFuWengEventType.ZaoYao ||
                    event.getEventType() == eDaFuWengEventType.Cal) {
                MonopolyProto.SkipEventRespMsg.Builder builder = MonopolyProto.SkipEventRespMsg.newBuilder();
                builder.setRet(GameErrorCode.E_ACTIVITY_DFW_EVENT_CAN_NOT_SKIP);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_SKIP_EVENT, builder);
                return;
            }
            if (event.getEventType() == eDaFuWengEventType.Boss) {
                if (userData.getFreeBattleTimes() - userData.getPreFreeBattleTimes() > 0) {
                    // 免费次数没用，到跨服判断boss是否死了
                    MonopolyProto.CrossSkipBossEventReqMsg.Builder builder = MonopolyProto.CrossSkipBossEventReqMsg.newBuilder();
                    builder.setActivityId(config.getActivityInfo().getActivityId());
                    builder.setUserId(player.getUserId());
                    builder.setServerId(player.getUserInfo().getOriginalServerId());
                    builder.setBossId(Integer.valueOf(userData.getExpandParam().split(";")[0]));
                    player.sendUnionActivityGroupPacket(Protocol.C_CROSS_DA_FU_WENG_SKIP_BOSS_EVENT, builder, config.getActivityInfo().getActivityId());
                    return;
                }
            }
            if (event.getEventType() == eDaFuWengEventType.Secret) {
                MonopolyProto.SkipEventRespMsg.Builder builder = MonopolyProto.SkipEventRespMsg.newBuilder();
                builder.setRet(GameErrorCode.E_ACTIVITY_DFW_EVENT_CAN_NOT_SKIP);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_SKIP_EVENT, builder);

                getLogger().error("DaFuWengMgr userId={} try skip Secret Event!", userData.getUserId());
                return;
            }


            // 处理一下现金礼包
            try {
                if (userData.getEventId() > 0) {
                    DFWEvent dfwEvent = config.getDfwEventMap().get(userData.getEventId());
                    if (dfwEvent.getEventType() == eDaFuWengEventType.Package) {
                        List<Integer> reTimesList = StringUtils.stringToIntegerList(userData.getExpandParam(), ",");
                        if (reTimesList.get(1) > 0) {
                            // 现金礼包还没买 添加到缓存列表
                            MallInfo mallInfo = NormalActivityMgr.getRMBActivityMallInfoByShopTypeAndExtendParam(config.getActivityInfo().getActivityId(), eShopType.DaFuWengMoneyMall.getValue(), dfwEvent.getParamList().get(1));
                            userData.getMoneyMallList().add(mallInfo.getMallId());
                        }
                        if (userData.isTenRoll()) {
                            userData.reducePackage(dfwEvent.getParamList().get(0), eShopType.DaFuWengGoldMall.getValue());
                        }
                        userData.reducePackage(dfwEvent.getParamList().get(1), eShopType.DaFuWengMoneyMall.getValue());
                    }
                }
            } catch (Exception ex) {
                getLogger().error(ex.getMessage());
            }
            // 处理跳过
            userData.setComplete(true);
            userData.setEventId(0);
            userData.setExpandParam("");
            // 返回
            MonopolyProto.SkipEventRespMsg.Builder builder = MonopolyProto.SkipEventRespMsg.newBuilder();
            builder.setRet(0);
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_SKIP_EVENT, builder);
        }
    }

    public static void tradeEvent(GamePlayer player) {
        synchronized (lockObject) {
            DFWConfig config = DaFuWengMgr.getDfwConfig();
            if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
                return;
            }
            DFWUserData userData = DaFuWengMgr.getUserData(config.getActivityInfo().getActivityId(), player.getUserId());
            if (userData.isComplete()) {
                MonopolyProto.HandleTradeEventRespMsg.Builder builder = MonopolyProto.HandleTradeEventRespMsg.newBuilder();
                builder.setRet(GameErrorCode.E_ACTIVITY_DFW_EVENT_HAD_HANDLE);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_TRADE_EVENT, builder);
                return;
            }
            int eventId = userData.getEventId();
            Map<Integer, DFWEvent> dfwEventMap = config.getDfwEventMap();
            DFWEvent event = dfwEventMap.get(eventId);
            if (event == null) {
                return;
            }
            if (event.getEventType() != eDaFuWengEventType.Trade) {
                MonopolyProto.HandleTradeEventRespMsg.Builder builder = MonopolyProto.HandleTradeEventRespMsg.newBuilder();
                builder.setRet(GameErrorCode.E_ACTIVITY_DFW_EVENT_TYPE_ERROR);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_TRADE_EVENT, builder);
                return;
            }

            Integer goodsId = event.getParamList().get(0);
            Integer goodsCount = event.getParamList().get(1);
            Property property = new Property(goodsId, BigInteger.valueOf(goodsCount));
            CurrencyModule currencyModule = player.getModule(CurrencyModule.class);
            if (!currencyModule.currencyIsEnough(property)) {
                MonopolyProto.HandleTradeEventRespMsg.Builder builder = MonopolyProto.HandleTradeEventRespMsg.newBuilder();
                builder.setRet(GameErrorCode.E_ACTIVITY_DFW_ITEM_NO_ENOUGH);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_TRADE_EVENT, builder);
                return;
            }

            // 扣道具，加奖励
            currencyModule.removeCurrency(property, eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengTradeEvent);
            String reward = event.getRewards();
            currencyModule.addCurrency(PropertyHelper.parseStringToProperty(reward), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengTradeEvent);

            // 改状态
            userData.setComplete(true);

            // 返回
            MonopolyProto.HandleTradeEventRespMsg.Builder builder = MonopolyProto.HandleTradeEventRespMsg.newBuilder();
            builder.setRet(0);
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_TRADE_EVENT, builder);
        }
    }

    /**
     * 造谣事件 造谣
     */
    public static int zaoYaoEvent(GamePlayer player, String unionUid) {
        synchronized (lockObject) {
            return ZaoYaoLogic.handleZaoYaoEvent(player, unionUid);
        }
    }

    /**
     * 处理造谣结果
     */
    public static void zaoYaoReturnFromCross(long userId, int type, int result, MonopolyProto.ZaoYaoSceneMsg sceneData, String unionUid) {
        synchronized (getLockObject()) {
            ZaoYaoLogic.zaoYaoResultFromCross(userId, type, result, sceneData, unionUid);
        }
    }

    /**
     * 使用造谣卡反击
     *
     * @return 是否通过使用校验
     */
    public static boolean zaoYaoCard(GamePlayer player, String param, MonopolyProto.UseCardRespMsg.Builder respMsg) {
        return ZaoYaoLogic.useZaoYaoCardStrikeBack(player, param, respMsg);
    }

    public static void zhuFuCard(GamePlayer player, int cardId, MonopolyProto.UseCardRespMsg.Builder respMsg) {
        // 看看自己是否有商会
        String unionUid = player.getUserInfo().getUnionUid();
        if (StringUtils.isNullOrEmpty(unionUid)) {
            respMsg.setRet(GameErrorCode.E_ACTIVITY_DFW_NO_UNION);
            return;
        }
        // 判断商会是否存在
        UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if (unionInfo == null) {
            respMsg.setRet(GameErrorCode.E_ACTIVITY_DFW_UNION_NO_FOUND);
            return;
        }
        if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(cardId, BigInteger.ONE), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengUseCardCost)) {
            respMsg.setRet(GameErrorCode.E_ACTIVITY_DFW_ITEM_NO_ENOUGH);
            return;
        }
        int activityId = dfwConfig.getActivityInfo().getActivityId();

       /* DFWUnionData unionData = getUnionData(activityId, unionUid);
        synchronized (getLockObject()) {
            checkUnionAddition(getDfwConfig(), unionUid);
            if (unionData.getAddition() >= getDfwConfig().getUnionMaxAddition()) {
                respMsg.setRet(GameErrorCode.E_ACTIVITY_DFW_ZHU_FU_MAX);
                return;
            }
            //祝福加成
            changeAddition(getDfwConfig().getZhuFuAddition(), unionData);
        }
        // 添加
        MonopolyProto.MonopolyPlayerMsg.Builder builder = MonopolyProto.MonopolyPlayerMsg.newBuilder();
        builder.setUserId(player.getUserId());
        builder.setPlayer(PlayerPb.parsePlayerBaseTempMsg(player.getUserInfo()));
        addUnionRecord(unionUid, getDfwConfig().getActivityInfo().getActivityId(), builder.build(), 2);
        // 同步
        syncZhuFu(player.getUserId(), player.getUserInfo().getNickName(), player.getUserInfo().getUnionUid());
        respMsg.setRet(0);*/
        CrossMonopolyProto.CrossDfwUseZhufuCardReqMsg.Builder reqMsg = CrossMonopolyProto.CrossDfwUseZhufuCardReqMsg.newBuilder();
        reqMsg.setActivityId(activityId);
        reqMsg.setUnionId(unionUid);
        reqMsg.setPlayerInfo(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId())));
        player.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_DA_FU_WENG_USE_ZHUFU_CARD, reqMsg, activityId);
    }

    /**
     * 打Boss
     *
     * @return 错误码
     */
    public static int battleBoss(DFWConfig config, GamePlayer gamePlayer, int bossId, int type, boolean useProp) {
        long userId = gamePlayer.getUserId();
        synchronized (getLockObject()) {
            DFWUserData userData = getUserData(config.getActivityInfo().getActivityId(), userId);
            if (System.currentTimeMillis() - userData.getLastAttackBossTime() < 500) {
                return GameErrorCode.E_ACTIVITY_ATTACK_BOSS_OFTEN;
            }

            // 【预扣除】
            // 预扣除消耗
            String cost = "";
            if (type == 1) {
                int preFreeBattleTimes = userData.getPreFreeBattleTimes();
                if (userData.getFreeBattleTimes() - preFreeBattleTimes <= 0) {
                    return GameErrorCode.E_ACTIVITY_DFW_FREE_BATTLE_NO_ENOUGH;
                }
                userData.setPreFreeBattleTimes(preFreeBattleTimes + 1);
            } else if (type == 2 || type == 3) {
                cost = config.getBattleCost();
                if (!gamePlayer.getModule(CurrencyModule.class).currencyIsEnough(PropertyHelper.parseStringToProperty(cost))) {
                    return GameErrorCode.E_ACTIVITY_DFW_ITEM_NO_ENOUGH;
                }
                gamePlayer.getModule(PreReduceModule.class).preReduce(cost);
            } else if (type == 4){
                //4.8新增一键击杀追捕卡消耗限制,只配了数量 物品从eItem拿
                Property costProperty = new Property();
                costProperty.addProperty(eItemId.DFW_ZHUI_BU_CARD.getValue(),BigInteger.valueOf(config.getFastBattleZhuiBuCardLimit()));
                cost = PropertyHelper.parsePropertyToString(costProperty);
                if (!gamePlayer.getModule(CurrencyModule.class).currencyIsEnough(costProperty)) {
                    return GameErrorCode.E_ACTIVITY_DFW_ITEM_NO_ENOUGH;
                }
                gamePlayer.getModule(PreReduceModule.class).preReduce(cost);
            }
            userData.setLastAttackBossTime(System.currentTimeMillis());
            // 预扣除buff
            int preYongBingTimes = userData.getPreYongBingTimes();
            int yongBingTimes = userData.getYongBingTimes();
            int buffTimes = preYongBingTimes >= yongBingTimes ? 0 : yongBingTimes - preYongBingTimes;
            if (type==4){    //4.8计算快速击杀的基本伤害,不使用原有佣兵卡的buff。
                buffTimes = 0;
            }
            userData.setPreYongBingTimes(preYongBingTimes + buffTimes);
            long yongBingCardNum = 0;
            if(useProp){
                // 佣兵卡数量
                UserBagItem userBagItem = gamePlayer.getModule(BagModule.class).getUserBagItem(eItemId.DFW_YONG_BING_CARD.getValue());
                if(userBagItem != null && userBagItem.getNum() > 0){
                    // 预扣除所有的佣兵卡
                    gamePlayer.getModule(PreReduceModule.class).preReduce(new Property(eItemId.DFW_YONG_BING_CARD.getValue(), BigInteger.valueOf(userBagItem.getNum())));
                    yongBingCardNum = userBagItem.getNum();
                }
            }
            // 【计算伤害】
            int damage = calDamage(userData, config, gamePlayer.getUserInfo().getUnionUid(),buffTimes);

            // 【发送到跨服】
            MonopolyProto.CrossBattleBossReqMsg.Builder builder = MonopolyProto.CrossBattleBossReqMsg.newBuilder();
            builder.setServerId(gamePlayer.getUserInfo().getOriginalServerId());
            builder.setUserId(userId);
            builder.setBossId(bossId);
            builder.setDamage(damage);
            builder.setActivityId(config.getActivityInfo().getActivityId());
            builder.setMonopolyPlayer(DaFuWengPb.parseMonopolyPlayerMsg(
                    gamePlayer.getUserId(),
                    PlayerPb.parsePlayerBaseTempMsg(gamePlayer.getUserInfo()).build()));
            builder.setType(type);
            builder.setBuffTimes(buffTimes);
            builder.setCost(cost);
            builder.setYongBingCardNum(yongBingCardNum);
            builder.setFastKillYongBingCardLimit(config.getFastBattleYongBingCardLimit());  //4.8快速击杀boss的佣兵卡最多使用配置
            gamePlayer.sendUnionActivityGroupPacket(Protocol.C_CROSS_DA_FU_WENG_BATTLE_BOSS, builder, config.getActivityInfo().getActivityId());
            return 0;
        }
    }

    /**
     * 初始化佣兵卡伤害
     */
    public static int initYongBingCardDamage(DFWConfig config, int cardId) {
        GoodsInfo goodsInfo = CommonMgr.getGoodsInfo(cardId);
        int eventId = Integer.valueOf(goodsInfo.getExtendParam().split(";")[0]);
        DFWEvent event = config.getDfwEventMap().get(eventId);
        return event.getParamList().get(0);
    }

    /**
     * 计算伤害
     */
    private static int calDamage(DFWUserData userData, DFWConfig config, String unionUid,int buffTimes) {
        int baseDamage = config.getBaseDamage();
        int yongBingDamage = config.getYongBingCardDamage() * buffTimes;
        int unionDamage = getBattleSkillAddition(config, unionUid);
        int patronsTalentAddDamage = 0;
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userData.getUserId());
        if (null != player) {
            patronsTalentAddDamage = player.getModule(PatronsModule.class).getTalentSkillAddition(eSkillType.DafuwengAddPatronsDamage.getValue(), 0);
            patronsTalentAddDamage += CurioMgr.getSkillAdditionBySkillType(eSkillType.DaFuWengBattleDamageSkill.getValue(), player, 0);
        }

        // 【实际伤害】=【基础伤害】+【其利断金加成】+【佣兵卡加成】+ 【门客天赋加成】+ 【藏宝加成】
        return baseDamage + yongBingDamage + unionDamage + patronsTalentAddDamage;
    }


    /**
     * 计算伤害 十连不使用佣兵卡
     */
    private static int calTenDamage(DFWUserData userData, DFWConfig config, String unionUid) {
        int baseDamage = config.getBaseDamage();
        int unionDamage = getBattleSkillAddition(config, unionUid);
        int patronsTalentAddDamage = 0;
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userData.getUserId());
        if (null != player) {
            patronsTalentAddDamage = player.getModule(PatronsModule.class).getTalentSkillAddition(eSkillType.DafuwengAddPatronsDamage.getValue(), 0);
            long addition = CurioMgr.getSkillAdditionBySkillType(eSkillType.DaFuWengBattleDamageSkill.getValue(), player, 0);
            if(addition > 0){
                baseDamage = BigDecimal.valueOf(baseDamage).multiply(BigDecimal.valueOf(1000 + addition)).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_UP).intValue();
            }
        }

        // 【实际伤害】=【基础伤害】+【其利断金加成】+ 【门客天赋加成】
        return baseDamage  + unionDamage + patronsTalentAddDamage;
    }

    /**
     * boss事件设置boss
     */
    public static void setBossEventBoss(GamePlayer player, int activityId, long userId, int bossId, MonopolyProto.RollDiceRespMsg rollMsg, int addNewsResult) {
        synchronized (getLockObject()) {
            DFWConfig config = getDfwConfig();
            DFWUserData userData = getUserData(activityId, userId);
            // 事件判断
            DFWEvent event = config.getDfwEventMap().get(userData.getEventId());
            if (event == null || event.getEventType() != eDaFuWengEventType.Boss) {
                return;
            }
            // 没有bossId才处理
            if (StringUtils.isNullOrEmpty(userData.getExpandParam())) {
                //修改成客户端不提示 参数修改为0 暂不剔除
                userData.setExpandParam(bossId + ";0");//bossId + 商会情报分享结果
                // 返回摇色子结果
                MonopolyProto.RollDiceRespMsg.Builder builder = rollMsg.toBuilder();
                builder.setRet(0);
                builder.setUserData(DaFuWengPb.getUserDataMsg(userData));
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_ROLL, builder);

                //分享成功记录一下
                if (addNewsResult == 1 || addNewsResult == 3) {
                    userData.setShareSuccess(true);
                }
            }
        }
    }

    /**
     * 造谣事件设置商会
     */
    public static void setZaoYaoEventUnion(GamePlayer player, int activityId, long userId,
                                           List<MonopolyProto.MonopolyUnionMsg> unionMsgList,
                                           MonopolyProto.RollDiceRespMsg rollMsg) {
        synchronized (getLockObject()) {
            MonopolyProto.RollDiceRespMsg.Builder builder = rollMsg.toBuilder();

            DFWConfig config = getDfwConfig();
            if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
                return;
            }

            DFWUserData userData = getUserData(activityId, userId);
            if (unionMsgList.size() == 2) {
                // 可以造谣
                userData.setZaoYaoOptionalList(DaFuWengPb.parseZaoYaoOptionalList(unionMsgList));
            } else {
                // 不能造谣（一般是商会数不够）
                userData.setEventId(getEmptyEventId(config));
                userData.setComplete(true);
                // 需要把造谣事件从里面移除（带tmp参数的是不要的）
                List<MonopolyProto.MovePositionMsg> tmpMovePosList = builder.getMovePositionListList();
                for (int i = 0; i < tmpMovePosList.size(); i++) {
                    MonopolyProto.MovePositionMsg tmpMovePos = tmpMovePosList.get(i);
                    MonopolyProto.MovePositionMsg.Builder movePos = MonopolyProto.MovePositionMsg.newBuilder();
                    List<MonopolyProto.EventResultMsg> tmpEventList = tmpMovePos.getEventListList();
                    List<MonopolyProto.EventResultMsg> eventList = new ArrayList<>();
                    for (int j = 0; j < tmpEventList.size(); j++) {
                        MonopolyProto.EventResultMsg tmpEventMsg = tmpEventList.get(j);
                        DFWEvent tmpEvent = config.getDfwEventMap().get(tmpEventMsg.getEventId());
                        if (tmpEvent != null && tmpEvent.getEventType() != eDaFuWengEventType.ZaoYao) {
                            eventList.add(tmpEventMsg);
                        }
                    }
                    movePos.setPositionIndex(tmpMovePos.getPositionIndex());
                    movePos.addAllEventList(eventList);
                    builder.setMovePositionList(i, movePos.build()); // 没办法删除，只能替换
                }
            }

            builder.setUserData(DaFuWengPb.getUserDataMsg(userData));
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_ROLL, builder);
        }
    }

    public static int getEmptyEventId(DFWConfig config) {
        for (DFWEvent dfwEvent : config.getDfwEventMap().values()) {
            if (dfwEvent.getEventType() == eDaFuWengEventType.Empty) {
                return dfwEvent.getEventId();
            }
        }
        return 0;
    }

    /**
     * 处理打boss结果
     */
    public static void handleBattleBossResult(int ret, int activityId, GamePlayer player, int type, int realDamage,
                                              boolean isKill, int buffTimes, String cost, String reward, long preReduceYongBingCardNum,
                                              long consumeYongBingCardNum, MonopolyProto.BossDataMsg bossDataMsg) {
        synchronized (getLockObject()) {
            DFWUserData userData = getUserData(activityId, player.getUserId());
            player.getModule(PreReduceModule.class).restorePreReduce(new Property(eItemId.DFW_YONG_BING_CARD.getValue(),BigInteger.valueOf(preReduceYongBingCardNum)));
            // 返回预扣除
            if (type == 1) {
                userData.setPreFreeBattleTimes(userData.getPreFreeBattleTimes() - 1);
                if (userData.getPreFreeBattleTimes() < 0) {
                    userData.setPreFreeBattleTimes(0);
                }
            } else if (type == 2 || type == 3 ||type == 4) {
                player.getModule(PreReduceModule.class).restorePreReduce(cost);
            } else {
                return;
            }
            userData.setPreYongBingTimes(userData.getPreYongBingTimes() - buffTimes);
            if (userData.getPreYongBingTimes() < 0) {
                userData.setPreYongBingTimes(0);
            }

            // 打失败了，返回
            if (ret != 0) {
                MonopolyProto.BattleBossRespMsg.Builder builder = MonopolyProto.BattleBossRespMsg.newBuilder();
                builder.setRet(ret);
                if (bossDataMsg != null) {
                    builder.setBossData(bossDataMsg);
                }
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_BATTLE_BOSS, builder);
                return;
            }

            // 打成功了，真实扣消耗
            if (type == 1) {
                userData.setFreeBattleTimes(userData.getFreeBattleTimes() - 1);
            } else if (type == 2 || type == 3 || type == 4) {
                player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(cost), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengBattleBoss);
            }
            int yongbingTimes = userData.getYongBingTimes() - buffTimes;
            if (yongbingTimes < 0) {
                yongbingTimes = 0;
            }
            userData.setYongBingTimes(yongbingTimes);

            // 消耗佣兵卡
            if(consumeYongBingCardNum > 0){
                Property yongBingProperty = new Property(eItemId.DFW_YONG_BING_CARD.getValue(),BigInteger.valueOf(consumeYongBingCardNum));
                player.getModule(CurrencyModule.class).removeCurrency(yongBingProperty, eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengBattleBossOneKeyConsume);
            }

            // 加奖励
            Property property = PropertyHelper.parseStringToProperty(reward);
            player.getModule(CurrencyModule.class).addCurrency(property, eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengBattleBoss);

            // 加积分
            BigInteger scoreAddValue = BigInteger.ZERO;
            for (Map.Entry<Integer, BigInteger> entry : property.getGoods().entrySet()) {
                if (eItemId.DFW_GOLDEN.getValue() == entry.getKey()) {
                    scoreAddValue = entry.getValue();
                    userData.setGoldScore(userData.getGoldScore() + entry.getValue().intValue());
                    player.notifyListener(eGamePlayerEventType.DaFuWengScoreRank.getValue(), userData.getGoldScore());
                    player.notifyListener(eGamePlayerEventType.DaFuWengUnionScoreRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, BigInteger.valueOf(userData.getGoldScore()), player.getUserInfo().getUnionUid()));
                }
            }

            if ((type == 1 || type == 2) && isKill) {
                //boss被击杀 跳过事件 分享到情报
                shareNews(player);
                userData.setComplete(true);
                userData.setExpandParam("");
            }

            // 排行榜
            userData.setTotalDamage(userData.getTotalDamage() + realDamage);
            player.notifyListener(eGamePlayerEventType.DaFuWengDamageRank.getValue(), userData.getTotalDamage());
            player.notifyListener(eGamePlayerEventType.DaFuWengUnionDamageRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, BigInteger.valueOf(userData.getTotalDamage()), player.getUserInfo().getUnionUid()));

            // 返回
            MonopolyProto.BattleBossRespMsg.Builder builder = MonopolyProto.BattleBossRespMsg.newBuilder();
            builder.setRet(ret);
            builder.setReward(PropertyHelper.parsePropertyToString(property));
            builder.setDamage(realDamage);
            builder.setBossData(bossDataMsg);
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_BATTLE_BOSS, builder);

            //log日志
            AutoLogMgr.add(new LogDFWDamage(activityId, userData.getUserId(), player.getUserInfo().getUnionUid(), realDamage, isKill, bossDataMsg.getBossId(),
                    bossDataMsg.getBossType(), reward, System.currentTimeMillis()));
        }
    }

    /**
     * 使用卡片
     *
     * @return 事件IdList
     */
    public static void useCard(GamePlayer player, int cardId, int count, String param) {
        synchronized (lockObject) {
            MonopolyProto.UseCardRespMsg.Builder respMsg = MonopolyProto.UseCardRespMsg.newBuilder();
            respMsg.setRet(0);
            GoodsInfo goodsInfo = CommonMgr.getGoodsInfo(cardId);
            if (goodsInfo == null) {
                return;
            }
            eDaFuWengCardType type = dfwConfig.getCardConfigMap().get(cardId);
            List<Map<Integer, Integer>> events = new ArrayList<>();
            Map<Integer, Integer> map = new ConcurrentHashMap<>();
            for (String s : goodsInfo.getExtendParam().split("\\|")) {
                List<Integer> list = StringUtils.stringToIntegerList(s, ";");
                map.put(list.get(0), list.get(1));
            }
            events.add(map);
            List<DFWEvent> dfwEvents = new ArrayList<>();
            for (int i = 0; i < count; i++) {
                dfwEvents.addAll(getEvents(dfwConfig, events));
            }
            if (type == eDaFuWengCardType.Gold) {
                useGoldCard(dfwEvents, player, cardId, count, respMsg);
            } else if (type == eDaFuWengCardType.YaoYan) {
                boolean success = zaoYaoCard(player, param, respMsg);
                if (success) {
                    return; // 使用造谣卡校验通过时，用另外的返回
                }
            } else if (type == eDaFuWengCardType.ZhuFu) {
                zhuFuCard(player, cardId, respMsg);
            } else if (type == eDaFuWengCardType.Energy) {
                useEnergyCard(dfwEvents, player, cardId, count, respMsg);
            } else if (type == eDaFuWengCardType.LuZhang) {
                LuZhangLogic.setLuZhang(param, player, cardId, respMsg);
            } else if (type == eDaFuWengCardType.YongBing) {
                useYongBingCard(dfwEvents, player, cardId, count, respMsg);
            } else if (type == eDaFuWengCardType.QingShen) {
                useQingShenCard(dfwEvents, player, cardId, count, respMsg);
            } else if (type == eDaFuWengCardType.HuoWu) {
                useHuoWuCard(dfwEvents, player, cardId, count, respMsg, map);
            } else if (type == eDaFuWengCardType.ZhuiBu) {
                respMsg.setRet(GameErrorCode.E_ACTIVITY_DFW_PARAM_ERROR);
            } else {
                return;
            }
            syncDFWUserData(player);
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_USE_CARD, respMsg);
        }
    }

    /**
     * 使用货物卡
     *
     * @param dfwEvents
     * @param player
     * @param cardId
     * @param count
     * @param respMsg
     * @param rewardGoodsMap
     */
    private static void useHuoWuCard(List<DFWEvent> dfwEvents, GamePlayer player, int cardId, int count, MonopolyProto.UseCardRespMsg.Builder respMsg, Map<Integer, Integer> rewardGoodsMap) {
        String unionUid = player.getUserInfo().getUnionUid();
        if (StringUtils.isNullOrEmpty(unionUid)) {
            //没有商会
            respMsg.setRet(GameErrorCode.E_UNION_NO_JOIN_UNION);
            return;
        }
        if (rewardGoodsMap.isEmpty()) {
            respMsg.setRet(GameErrorCode.E_ACTIVITY_DFW_COLLECT_FULL);
        }
        if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(cardId, BigInteger.valueOf(count)), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengUseCardCost)) {
            respMsg.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
            return;
        }
        List<Map<Integer, Integer>> canRewardList = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            canRewardList.add(rewardGoodsMap);
        }
        List<DFWEvent> events = getEvents(getDfwConfig(), canRewardList);
        Property allProperty = new Property();
        for (DFWEvent dfwEvent : events) {
            Property property = PropertyHelper.parseStringToProperty(dfwEvent.getRewards());
            allProperty.addProperty(property);
            respMsg.addEventIdList(dfwEvent.getEventId());
        }
        collectGoods(unionUid, allProperty, player.getUserId());
    }

    /**
     * 使用请神卡
     *
     * @param dfwEvents
     * @param player
     * @param cardId
     * @param count
     * @param respMsg
     */
    private static void useQingShenCard(List<DFWEvent> dfwEvents, GamePlayer player, int cardId, int count, MonopolyProto.UseCardRespMsg.Builder respMsg) {
        if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(cardId, BigInteger.valueOf(count)), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengUseCardCost)) {
            respMsg.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
            return;
        }
        DFWUserData userData = getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId());
        for (DFWEvent dfwEvent : dfwEvents) {
            addGodTimes(userData, dfwEvent);
            respMsg.addEventIdList(dfwEvent.getEventId());
        }
    }

    public static void addGodTimes(DFWUserData userData, DFWEvent dfwEvent) {
        int godId = dfwEvent.getEventId();
        // 拿神仙生效次数
        List<DFWGodData> tmpGodList = new ArrayList<>();
        tmpGodList.add(new DFWGodData(dfwEvent.getEventId(), 1));
        int moveTimes = getGodSkillAddition(getDfwConfig(), tmpGodList).get(3);
        boolean isHave = false;
        for (DFWGodData dfwGodData : userData.getDfwGodDataList()) {
            if (dfwGodData.getGodId() == godId) {
                isHave = true;
                dfwGodData.setGodMoveTimes(dfwGodData.getGodMoveTimes() + moveTimes);
                break;
            }
        }
        if (!isHave) {
            userData.getDfwGodDataList().add(new DFWGodData(godId, moveTimes));
        }
        userData.setUpdateOption();
    }

    /**
     * 使用佣兵卡
     *
     * @param dfwEvents
     * @param player
     * @param cardId
     * @param count
     * @param respMsg
     */
    private static void useYongBingCard(List<DFWEvent> dfwEvents, GamePlayer player, int cardId, int count, MonopolyProto.UseCardRespMsg.Builder respMsg) {
        if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(cardId, BigInteger.valueOf(count)), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengUseCardCost)) {
            respMsg.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
            return;
        }
        for (DFWEvent dfwEvent : dfwEvents) {
            respMsg.addEventIdList(dfwEvent.getEventId());
        }
        DFWUserData userData = getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId());
        userData.setYongBingTimes(userData.getYongBingTimes() + count);
    }

    /**
     * 使用体力卡
     *
     * @param dfwEvents
     * @param player
     * @param cardId
     * @param count
     * @param respMsg
     */
    private static void useEnergyCard(List<DFWEvent> dfwEvents, GamePlayer player, int cardId, int count, MonopolyProto.UseCardRespMsg.Builder respMsg) {
        if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(cardId, BigInteger.valueOf(count)), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengUseCardCost)) {
            respMsg.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
            return;
        }
        int energy = 0;
        for (DFWEvent dfwEvent : dfwEvents) {
            energy += dfwEvent.getParamList().get(0);
            respMsg.addEventIdList(dfwEvent.getEventId());
        }
        recoveryPower(player);
        DFWUserData userData = getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId());
        userData.setEnergy(userData.getEnergy() + energy);
    }


    /**
     * 使用金币卡
     *
     * @param dfwEvents
     * @param player
     * @param cardId
     * @param count
     * @param respMsg
     */
    private static void useGoldCard(List<DFWEvent> dfwEvents, GamePlayer player, int cardId, int count, MonopolyProto.UseCardRespMsg.Builder respMsg) {
        if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(cardId, BigInteger.valueOf(count)), eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengUseCardCost)) {
            respMsg.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
            return;
        }
        Property reward = new Property();
        for (DFWEvent dfwEvent : dfwEvents) {
            reward.addProperty(PropertyHelper.parseStringToProperty(dfwEvent.getRewards()));
            respMsg.addEventIdList(dfwEvent.getEventId());
        }
        DFWUserData userData = getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId());
        int golden = reward.getCountByGoodsId(eItemId.DFW_GOLDEN.getValue()).intValue();
        userData.setGoldScore(userData.getGoldScore() + golden);
        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengUseCardReward);
        player.notifyListener(eGamePlayerEventType.DaFuWengScoreRank.getValue(), userData.getGoldScore());
        player.notifyListener(eGamePlayerEventType.DaFuWengUnionScoreRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, BigInteger.valueOf(userData.getGoldScore()), player.getUserInfo().getUnionUid()));
    }

    /**
     * 本服处理来自跨服的造谣
     */
    public static int zaoYaoFromCross(String unionUid, int activityId, MonopolyProto.MonopolyPlayerMsg doPlayer, MonopolyProto.ZaoYaoSceneMsg.Builder sceneMsg) {
        synchronized (getLockObject()) {
            return ZaoYaoLogic.zaoYaoFromCross(unionUid, activityId, doPlayer, sceneMsg);
        }
    }

    /**
     * 获取全部unionRecord
     */
    private static List<DFWUnionRecord> getUnionRecordList(int type, int activityId, String unionUid) {
        return new ArrayList<>();
    }

    /**
     * 获取造谣祝福记录
     *
     * @param type 1造谣，2祝福
     */
    public static List<DFWUnionRecord> getUnionRecord(int activityId, String unionUid, int type) {
        synchronized (getLockObject()) {
            int maxCount = 0;
            List<DFWUnionRecord> list = getUnionRecordList(type, activityId, unionUid);
            DFWConfig config = getDfwConfig();
            if (type == 1) {
                maxCount = config.getZaoYaoNewsCount();
            } else if (type == 2) {
                maxCount = config.getZhuFuNewsCount();
            }

            List<DFWUnionRecord> retList;
            if (list.size() <= maxCount) {
                retList = new ArrayList<>(list);
            } else {
                int size = list.size();
                retList = new ArrayList<>(list.subList(size - maxCount, size));
            }
            Collections.reverse(retList);
            return retList;
        }
    }


    /**
     * 更换人偶
     *
     * @param player
     * @param dollId 人偶id
     * @return
     */
    public static int changeDoll(GamePlayer player, int dollId) {
        synchronized (lockObject) {
            DFWConfig config = DaFuWengMgr.getDfwConfig();
            if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
                return GameErrorCode.E_ACTIVITY_NO_FOUND;
            }
            if (dollId != 0 && !config.getDollIdList().contains(dollId)) {
                return GameErrorCode.E_ACTIVITY_DFW_DOLL_NO_FOUND;
            }
            DFWUserData userData = DaFuWengMgr.getUserData(config.getActivityInfo().getActivityId(), player.getUserId());
            List<DFWDollData> dollList = userData.getDollList();
            for (DFWDollData dollData : dollList) {
                if (dollData.getDollId() == dollId) {
                    //人偶过期
                    if (dollData.getExpireTime() != 0 && System.currentTimeMillis() >= dollData.getExpireTime()) {
                        return GameErrorCode.E_ACTIVITY_DFW_DOLL_OVER_TIME;
                    } else {
                        userData.setDollId(dollId);
                        return 0;
                    }
                }
            }
            //未拥有
            return GameErrorCode.E_ACTIVITY_DFW_DOLL_NO_HAVE;
        }
    }

    /**
     * 使用道具
     *
     * @param goodId
     * @param count
     * @param player
     * @param respMsg
     */
    public static void useGood(int goodId, int count, GamePlayer player, MonopolyProto.UseDFWGoodRespMsg.Builder respMsg) {
        synchronized (lockObject) {
            respMsg.setRet(0);
            if (goodId == dfwConfig.getEnergyItemId()) {
                //使用体力道具
                GoodsInfo goodsInfo = CommonMgr.getGoodsInfo(goodId);
                if (goodsInfo == null) {
                    respMsg.setRet(GameErrorCode.E_GOODS_NO_EXIST);
                    respMsg.setParam("0");
                    return;
                }
                int energy = goodsInfo.getParamList().get(0).intValue();
                if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(goodId, BigInteger.valueOf(count)),
                        eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengUseGood)) {
                    respMsg.setRet(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
                    respMsg.setParam("0");
                    return;
                }
                DFWUserData userData = getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId());
                userData.setEnergy(energy * count + userData.getEnergy());
                respMsg.setParam(String.valueOf(energy * count));
                syncDFWUserData(player);
            }
        }
    }

    /**
     * boss情报分享
     */
    public static void shareNews(GamePlayer player) {
        synchronized (lockObject) {
            MonopolyProto.GiveUpBossShareNewsRespMsg.Builder respMsg = MonopolyProto.GiveUpBossShareNewsRespMsg.newBuilder();
            int ret = 0;
            int bossId = 0;
            DFWUserData userData = getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId());
            String unionUid = player.getUserInfo().getUnionUid();
            if (userData.isShareSuccess() || StringUtils.isNullOrEmpty(unionUid)) {
                respMsg.setRet(ret);
                respMsg.setAddNewsResult(0);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_GIVE_UP_BOSS_SHARE_NEWS, respMsg);
                skipEvent(player);
                userData.setShareSuccess(false);
                return;
            }
            try {
                bossId = Integer.parseInt(userData.getExpandParam().split(";")[0]);
            } catch (Exception e) {
                getLogger().error("param error. {}", userData.getExpandParam());
                respMsg.setRet(0);
                respMsg.setAddNewsResult(0);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_GIVE_UP_BOSS_SHARE_NEWS, respMsg);
                skipEvent(player);
                return;
            }
            skipEvent(player);
            MonopolyProto.ShareNewsToCrossReqMsg.Builder reqMsg = MonopolyProto.ShareNewsToCrossReqMsg.newBuilder();
            reqMsg.setActivityId(dfwConfig.getActivityInfo().getActivityId());
            reqMsg.setUnionUid(unionUid);
            reqMsg.setBossId(bossId);
            player.sendUnionActivityGroupPacket(Protocol.C_CROSS_DA_FU_WENG_BOSS_SHARE_NEWS, reqMsg, dfwConfig.getActivityInfo().getActivityId());

        }
    }

    /**
     * 获取情报事件信息 商会成员列表
     *
     * @param player
     * @param unionUid
     * @param itemId
     */
    public static void getCollectEventMemberList(GamePlayer player, String unionUid, int itemId) {
        CrossMonopolyProto.CrossDfwCollectEventMemberMsg.Builder req = CrossMonopolyProto.CrossDfwCollectEventMemberMsg.newBuilder();
        req.setActivityId(dfwConfig.getActivityInfo().getActivityId());
        req.setUnionId(unionUid);
        req.setItemId(itemId);
        Map<Long, CrossUnionMember> unionMemberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
        if (unionMemberMap != null) {
            for (Long memberId : new ArrayList<>(unionMemberMap.keySet())) {
                req.addMemberId(memberId);
            }
        }
        player.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_DA_FU_WENG_UNION_COLLECT_MEMBER_MSG, req, dfwConfig.getActivityInfo().getActivityId());
    }

    /**
     * 体力恢复
     *
     * @param player
     */
    public static void recoveryPower(GamePlayer player) {
        synchronized (lockObject) {
            DFWConfig config = getDfwConfig();
            if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
                return;
            }
            DFWUserData userData = DaFuWengMgr.getUserData(config.getActivityInfo().getActivityId(), player.getUserId());
            CalcPowerResult calcPowerResult = PowerHelper.calcPower(userData.getLastRecoveryTime() / 1000, config.getEnergyRecoverySecond(), 1, config.getMaxEnergy(), userData.getEnergy());
            userData.setEnergy(calcPowerResult.getCurPower());
            userData.setLastRecoveryTime(calcPowerResult.getLastRecoverTime() * 1000);
        }
    }

    /**
     * 初始化技能Map
     */
    public static Map<eDaFuWengEventType, List<DFWEvent>> buildSkillMap(Map<Integer, DFWEvent> eventMap) {
        Map<eDaFuWengEventType, List<DFWEvent>> map = new ConcurrentHashMap<>();
        map.put(eDaFuWengEventType.MapSkill, new ArrayList<>());
        map.put(eDaFuWengEventType.BattleSkill, new ArrayList<>());
        map.put(eDaFuWengEventType.OpenBoxSkill, new ArrayList<>());
        map.put(eDaFuWengEventType.RecoverySkill, new ArrayList<>());
        map.put(eDaFuWengEventType.DollSkill1, new ArrayList<>());
        map.put(eDaFuWengEventType.DollSKill2, new ArrayList<>());
        map.put(eDaFuWengEventType.GodSkill, new ArrayList<>());
        map.put(eDaFuWengEventType.MoveSkill, new ArrayList<>());
        for (DFWEvent event : eventMap.values()) {
            eDaFuWengEventType eventType = event.getEventType();
            if (map.containsKey(eventType)) {
                // 配置了升级参数的技能只要存0级的
                if (eventType == eDaFuWengEventType.BattleSkill || eventType == eDaFuWengEventType.OpenBoxSkill) {
                    if (event.getUpgradeParamList().get(0) != 0) {
                        continue;
                    }
                }
                map.get(event.getEventType()).add(event);
            }
        }
        return map;
    }

    /**
     * 根据金币获取地图加成
     *
     * @param goldScore 金币积分数
     * @return 千分比，List：0金币加成
     */
    public static List<Integer> getMapSkillAddition(DFWConfig config, int goldScore) {
        List<Integer> addition = new ArrayList<>();
        addition.add(0);
        // 找当前地图
        DFWMapConfig lastMap = null;
        for (DFWMapConfig mapConfig : config.getDfwMapConfigList()) {
            if (goldScore >= mapConfig.getUnlockGold()) {
                lastMap = mapConfig;
            } else {
                break;
            }
        }
        if (lastMap == null) {
            return addition;
        }
        // 找技能事件
        if (lastMap.getSkill() == 0) {
            return addition;
        }
        DFWEvent event = config.getDfwEventMap().get(lastMap.getSkill());
        if (event == null) {
            getLogger().error("DaFuWengMgr getMapSkillAddition error! Map skill mapper DFWEvent no found!");
            return addition;
        }
        addition.set(0, event.getParamList().get(0));
        return addition;
    }

    /**
     * 获取战斗技能加成（其利断金）
     *
     * @return 战斗伤害加成值
     */
    public static int getBattleSkillAddition(DFWConfig config, String unionUid) {
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return 0;
        }
        int skillEventId = getBattleSkillEventId(config, unionUid);
        DFWEvent skill = config.getDfwEventMap().get(skillEventId);
        if (skill == null) {
            return 0;
        } else {
            return skill.getParamList().get(0);
        }
    }

    /**
     * 获取当前其利断金事件ID
     */
    public static int getBattleSkillEventId(DFWConfig config, String unionUid) {
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return 0;
        }
        return 0;
      /*  DFWUnionData unionData = getUnionData(config.getActivityInfo().getActivityId(), unionUid);
        // 找到0级技能
        List<DFWEvent> skillList = config.getSkillMap().get(eDaFuWengEventType.BattleSkill);
        int count = getIronCollectCount(unionData);
        // 判断技能升级
        DFWEvent skill = skillList.get(0);
        for (int i = 0; i < 100; i++) {
            int upgradeCount = skill.getUpgradeParamList().get(1);
            if (count >= upgradeCount && upgradeCount != 0) {
                // 能升级
                DFWEvent tmpEvent = config.getDfwEventMap().get(skill.getUpgradeParamList().get(2));
                if (tmpEvent != null) {
                    skill = tmpEvent;
                } else {
                    getLogger().error("DaFuWengMgr getBattleSkillAddition error! Upgrade DFWEvent no found!");
                    break;
                }
            } else {
                // 不够升级
                break;
            }
        }
        return skill.getEventId();*/
    }

    /**
     * 获取神的加成
     *
     * @return List：0金币加成千分比，1银币加成千分比，2随机好的恢复体力值，3持续次数
     */
    public static List<Integer> getGodSkillAddition(DFWConfig config, List<DFWGodData> godList) {
        List<Integer> addition = new ArrayList<>();
        addition.add(0);
        addition.add(0);
        addition.add(0);
        addition.add(0);
        if (godList.size() == 0) {
            return addition;
        }
        // 找神事件
        for (DFWGodData godData : godList) {
            int godId = godData.getGodId();
            DFWEvent event = config.getDfwEventMap().get(godId);
            if (event == null || event.getEventType() != eDaFuWengEventType.God) {
                getLogger().error("DaFuWengMgr getGodSkillAddition error! God Event no found!");
                continue;
            }
            // 找技能
            int skillId = event.getParamList().get(0);
            DFWEvent skill = config.getDfwEventMap().get(skillId);
            if (skill.getEventType() == eDaFuWengEventType.RecoverySkill) {
                addition.set(3, skill.getParamList().get(2));
                int random = new Random().nextInt(1000);
                if (random < skill.getParamList().get(1)) {
                    addition.set(2, addition.get(2) + skill.getParamList().get(0));
                }
            } else if (skill.getEventType() == eDaFuWengEventType.GodSkill) {
                addition.set(0, addition.get(0) + skill.getParamList().get(0));
                addition.set(3, skill.getParamList().get(2));
            } else {
                getLogger().error("DaFuWengMgr getGodSkillAddition error! God Skill Type error!");
                continue;
            }
        }
        return addition;
    }

    /**
     * 人偶过期检测（帮他换形象）
     */
    public static void checkDollExpire(DFWUserData userData) {
        int dollId = userData.getDollId();
        List<DFWDollData> dollList = userData.getDollList();
        long now = System.currentTimeMillis();
        for (DFWDollData dollData : dollList) {
            if (dollData.getDollId() == dollId) {
                // 当前使用的人偶过期了，换回默认形象
                long expireTime = dollData.getExpireTime();
                if (expireTime != 0 && expireTime <= now) {
                    userData.setDollId(getDfwConfig().getDefaultDollId());
                }
                break;
            }
        }
    }

    /**
     * 获取人偶加成
     *
     * @return List：0建筑基础金币加成
     */
    public static List<Integer> getDollSkillAddition(DFWConfig config, List<DFWDollData> dollDataList) {
        List<Integer> addition = new ArrayList<>();
        addition.add(0);
        Map<Integer, DFWEvent> eventMap = config.getDfwEventMap();
        long now = System.currentTimeMillis();
        for (int i = 0; i < dollDataList.size(); i++) {
            DFWDollData dollData = dollDataList.get(i);
            if (dollData.getExpireTime() != 0 && dollData.getExpireTime() < now) {
                // 调过已过期人偶
                continue;
            }
            GoodsInfo goodsInfo = CommonMgr.getGoodsInfo(dollData.getDollId());
            if (goodsInfo == null) {
                getLogger().error("DaFuWengMgr getDollSkillAddition error! Doll goods no found!");
                continue;
            }
            if (goodsInfo.getExtendParam().equals("0")) {
                continue;
            }
            DFWEvent event = eventMap.get(Integer.valueOf(goodsInfo.getExtendParam()));
            if (event == null) {
                getLogger().error("DaFuWengMgr getDollSkillAddition error! Doll event no found!");
                continue;
            }
            if (event.getEventType() != eDaFuWengEventType.DollSkill1 && event.getEventType() != eDaFuWengEventType.DollSKill2) {
                getLogger().error("DaFuWengMgr getDollSkillAddition error! Skill event type error!");
                continue;
            }
            addition.set(0, addition.get(0) + event.getParamList().get(0));
        }
        return addition;
    }

    /**
     * 获取坐骑技能加成
     *
     * @return List：0增加的移动步数，1持续次数
     */
    public static List<Integer> getVehicleSkillAddition(DFWConfig config, int vehicleId) {
        List<Integer> addition = new ArrayList<>();
        addition.add(0);
        addition.add(0);
        DFWEvent event = config.getDfwEventMap().get(vehicleId);
        if (event == null || event.getEventType() != eDaFuWengEventType.Vehicle) {
            getLogger().error("DaFuWengMgr getVehicleSkillAddition error! Skill no found or event type error!");
            return addition;
        }
        int skillId = event.getParamList().get(0);
        DFWEvent skill = config.getDfwEventMap().get(skillId);
        if (skill == null || skill.getEventType() != eDaFuWengEventType.MoveSkill) {
            getLogger().error("DaFuWengMgr getVehicleSkillAddition error! Skill type error!");
            return addition;
        }
        addition.set(0, skill.getParamList().get(0));
        addition.set(1, skill.getParamList().get(2));
        return addition;
    }

    /**
     * 获取商会加成
     *
     * @return List：0金币加成
     */
    public static List<Integer> getUnionSkillAddition(DFWConfig config, String unionUid) {
        List<Integer> addition = new ArrayList<>();
        addition.add(0);
        Map<String, MonopolyProto.UnionDataMsg> msgMap = unionMsgMap.get(config.getActivityInfo().getActivityId());
        if (msgMap != null) {
            MonopolyProto.UnionDataMsg unionDataMsg = msgMap.get(unionUid);
            if (unionDataMsg != null) {
                addition.set(0, unionDataMsg.getUnionAddition());
            }
        }
        return addition;
    }

    private static int getTimeMark() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        String monthStr = month < 10 ? "0" + month : month + "";
        String dayStr = day < 10 ? "0" + day : day + "";
        String timeStr = year + monthStr + dayStr;
        return Integer.valueOf(timeStr);
    }

    /**
     * 造谣卡使用目标商会列表
     *
     * @param player
     */
    public static void GetZaoYaoCardUseUnionList(GamePlayer player) {
        synchronized (lockObject) {
            MonopolyProto.GetZaoYaoCardUseUnionListRespMsg.Builder respMsg = MonopolyProto.GetZaoYaoCardUseUnionListRespMsg.newBuilder();
            DFWUserData userData = getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId());
            // 看看自己是否有商会
            String unionUid = player.getUserInfo().getUnionUid();
            if (StringUtils.isNullOrEmpty(unionUid)) {
                respMsg.setRet(GameErrorCode.E_ACTIVITY_DFW_NO_UNION);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_GET_ZAOYAO_CARD_USE_UNION_LIST, respMsg);
                return;
            }
            if (userData.getZaoYaoCardOptionalList() == null || userData.getZaoYaoCardOptionalList().size() == 0) {
                // 到跨服拿造谣可选商会
                MonopolyProto.CrossGetZaoYaoCardCardUnionListReqMsg.Builder builder = MonopolyProto.CrossGetZaoYaoCardCardUnionListReqMsg.newBuilder();
                builder.setActivityId(getDfwConfig().getActivityInfo().getActivityId());
                builder.setServerId(player.getUserInfo().getOriginalServerId());
                builder.setUnionUid(player.getUserInfo().getUnionUid());
                player.sendUnionActivityGroupPacket(Protocol.C_CROSS_DA_FU_WENG_GET_ZAO_YAO_CARD_UNION_LIST, builder, getDfwConfig().getActivityInfo().getActivityId());
                return;
            }
            respMsg.setRet(0);
            respMsg.addAllUnionMsg(DaFuWengPb.parseMonopolyUnionMsgList(userData.getZaoYaoCardOptionalList()));
            player.sendPacket(ClientProtocol.U_DA_FU_WENG_GET_ZAOYAO_CARD_USE_UNION_LIST, respMsg);
        }
    }

    /**
     * 从跨服拿造谣卡商会列表
     */
    public static void GetZaoYaoCardUseUnionListFromCross(GamePlayer player, List<MonopolyProto.MonopolyUnionMsg> unionMsgList) {
        synchronized (getLockObject()) {
            MonopolyProto.GetZaoYaoCardUseUnionListRespMsg.Builder respMsg = MonopolyProto.GetZaoYaoCardUseUnionListRespMsg.newBuilder();
            DFWUserData userData = getUserData(dfwConfig.getActivityInfo().getActivityId(), player.getUserId());
            if (unionMsgList.isEmpty()) {
                respMsg.setRet(GameErrorCode.E_ACTIVITY_DFW_NO_ENOUGH_UNION_TO_USE_ZAO_YAO_CARD);
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_GET_ZAOYAO_CARD_USE_UNION_LIST, respMsg);
                return;
            }
            if (userData.getZaoYaoCardOptionalList() == null || userData.getZaoYaoCardOptionalList().size() == 0) {
                userData.setZaoYaoCardOptionalList(DaFuWengPb.parseZaoYaoOptionalList(unionMsgList));
                respMsg.setRet(0);
                respMsg.addAllUnionMsg(DaFuWengPb.parseMonopolyUnionMsgList(userData.getZaoYaoCardOptionalList()));
                player.sendPacket(ClientProtocol.U_DA_FU_WENG_GET_ZAOYAO_CARD_USE_UNION_LIST, respMsg);
            }
        }
    }

    /**
     * 使用造谣卡造谣
     *
     * @param index
     * @param player
     */
    public static void useCardZaoYao(int index, GamePlayer player) {
        synchronized (lockObject) {
            ZaoYaoLogic.useCardZaoYao(player, index);
        }
    }

    /**
     * 获取收集事件集满奖励
     */
    public static void getCollectReward(GamePlayer player, int itemId) {
        int ret = 0;
        Property reward = new Property();

        DFWConfig config = getDfwConfig();
        long userId = player.getUserId();
        DFWUserData userData = getUserData(config.getActivityInfo().getActivityId(), userId);
        Integer times = userData.getRewardCollectionMap().get(itemId);
        // 判断次数
        if (times != null && times > 0) {
            // 找到收集事件为itemId的建筑
            DFWBuildingConfig buildingConfig = null;
            for (DFWBuildingConfig tmpBuildingConfig : config.getDfwBuildingConfigMap().values()) {
                String collectTask = tmpBuildingConfig.getCollectTask();
                if (collectTask.equals("0")) {
                    continue;
                }
                String[] taskList = collectTask.split("=");
                int tmpItemId = Integer.valueOf(taskList[0]);
                if (tmpItemId == itemId) {
                    buildingConfig = tmpBuildingConfig;
                    break;
                }
            }
            if (buildingConfig != null) {
                reward = PropertyHelper.parseStringToProperty(buildingConfig.getCollectRewards());
                reward.rideProperty(times);
                // 扣次数
                userData.getRewardCollectionMap().put(itemId, 0);
                userData.setUpdateOption();
                // 奖励加背包
                player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.DaFuWeng, eLogMoneyType.DaFuWengGetCollectReward);
            } else {
                getLogger().error("DaFuWengMgr getCollectReward error! no building has item collect task but have reward times.");
                ret = GameErrorCode.E_ACTIVITY_DFW_PARAM_ERROR;
            }
        } else {
            ret = GameErrorCode.E_ACTIVITY_DFW_COLLECT_REWARD_TIMES_NO_ENOUGH;
        }

        syncDFWUserData(player);

        MonopolyProto.GetCollectItemRewardRespMsg.Builder builder = MonopolyProto.GetCollectItemRewardRespMsg.newBuilder();
        builder.setRet(ret);
        if (ret == 0) {
            builder.setReward(PropertyHelper.parsePropertyToString(reward));
        }
        player.sendPacket(ClientProtocol.U_DA_FU_WENG_GET_COLLECT_REWARD, builder);
    }


    public static CollectEventResult doCollectEvent(String unionUid, Property property, long userId) {
        CollectEventResult eventResult = new CollectEventResult();
        if (StringUtils.isNullOrEmpty(unionUid)) {
            eventResult.setCanDoCollectEvent(false);
            eventResult.setUnionCollectReachReward(false);
            return eventResult;
        }
        Property realCollect = new Property();
        for (Map.Entry<Integer, BigInteger> entry : property.getGoods().entrySet()) {
            Integer goodsId = entry.getKey();
            realCollect.addProperty(goodsId, entry.getValue());
        }
        if (realCollect.isNothing()) {
            eventResult.setCanDoCollectEvent(false);
            eventResult.setUnionCollectReachReward(false);
            return eventResult;
        }
        int beforeBattleSkillId = DaFuWengMgr.getBattleSkillEventId(dfwConfig, unionUid);
        // 收集操作
        CollectEventResult collectEventResult = DaFuWengMgr.collectGoods(unionUid, realCollect, userId);
        int afterBattleSkillId = DaFuWengMgr.getBattleSkillEventId(dfwConfig, unionUid);
        // 对比收集前后其利断金是否变化
        if (afterBattleSkillId != beforeBattleSkillId) {
            collectEventResult.setNewBattleSkillId(afterBattleSkillId);
        }
        return collectEventResult;
    }

    public static CollectEventResult collectGoods(String unionId, Property property, long userId) {
        CollectEventResult eventResult = new CollectEventResult();
        eventResult.setCanDoCollectEvent(true);
        CrossMonopolyProto.CrossDfwCollectReqMsg.Builder msg = CrossMonopolyProto.CrossDfwCollectReqMsg.newBuilder();
        msg.setActivityId(dfwConfig.getActivityInfo().getActivityId());
        msg.setUnionId(unionId);
        msg.setReward(PropertyHelper.parsePropertyToString(property));
        msg.setPlayerInfo(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(userId, GameServer.getInstance().getServerId())));
        CollectEventResult result = CrossReqMgr.sendMsg(userId, msg, dfwConfig.getActivityInfo().getActivityId());
        return result;
    }

    /**
     * 同步商会情报红点
     */
    public static void syncUnionNewsRedHot(GamePlayer player, String unionUid) {
        long userId = player.getUserId();
        Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
        if (memberMap == null) {
            return;
        }
        WorldMessageProto.RedHotNotifyMsg.Builder redHotMsg = WorldMessagePb.parseRedHotNotifyMsg(eRedHotNotifyType.DaFuWengUnionNews.getValue(), 1, "");
        for (UnionMember member : memberMap.values()) {
//            if (member.getUserId() == userId) {
//                continue; // 现在红点也要推给发现boss的人了
//            }
            GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(member.getUserId());
            if (onlinePlayer != null) {
                onlinePlayer.sendPacket(ClientProtocol.U_RED_HOT_NOTIFY, redHotMsg);
            }
        }
    }

    /**
     * 清空3天前的活动数据
     */
    public static void cleanMemory() {
        long now = System.currentTimeMillis();

        int noRemoveId = 0;
        if (dfwConfig != null) {
            ActivityInfo info = dfwConfig.getActivityInfo();
            if (now - info.getEndShowTime() * 1000 < 12 * DateHelper.HOUR_MILLIONS) {
                noRemoveId = info.getActivityId();
            }
        }

        List<Integer> removeId = new ArrayList<>();
        for (Map.Entry<Integer, Map<Long, DFWUserData>> entry : userDataMap.entrySet()) {
            if (entry.getKey() != noRemoveId) {
                removeId.add(entry.getKey());
            }
        }

        for (int activityId : removeId) {
            userDataMap.remove(activityId);
            getLogger().info("DaFuWengMgr cleanMemory : remove activity from userDataMap, activityId={}", activityId);
        }

    }


    /**
     * 通过道具ID获取任意一个收集类事件ID
     *
     * @return 0：找不到
     */
    public static int getCollectEventByGoodsId(int goodsId) {
        DFWConfig dfwConfig = getDfwConfig();
        if (dfwConfig == null) {
            return 0;
        }
        for (DFWEvent event : dfwConfig.getDfwEventMap().values()) {
            if (event.getEventType() == eDaFuWengEventType.CollectGoods) {
                String rewards = event.getRewards();
                List<Integer> list = StringUtils.stringToIntegerList(rewards, "=");
                if (list.size() > 0 && list.get(0) == goodsId) {
                    return event.getEventId();
                }
            }
        }
        return 0;
    }

    /**
     * 获取收集某个道具的建筑ID
     */
    public static int getBuildingIdByGoodsId(int goodsId) {
        DFWConfig dfwConfig = getDfwConfig();
        Map<Integer, DFWBuildingConfig> buildingConfigMap = dfwConfig.getDfwBuildingConfigMap();
        for (DFWBuildingConfig buildingConfig : buildingConfigMap.values()) {
            if (!"0".equals(buildingConfig.getCollectTask())) {
                String collectTask = buildingConfig.getCollectTask();
                List<Integer> list = StringUtils.stringToIntegerList(collectTask, "=");
                if (list.get(0) == goodsId) {
                    return buildingConfig.getBuildingId();
                }
            }
        }
        return 0;
    }

    /**
     * 同步配置和数据
     */
    public static void syncDataAndConfig(GamePlayer player) {
        DaFuWengMgr.syncDFWConfig(player);
        DaFuWengMgr.recoveryPower(player);
        DaFuWengMgr.syncDFWUserData(player);
        uploadDollMsg(player,DaFuWengPb.parseUnionMemberDollTemp(getUserData(dfwConfig.getActivityInfo().getActivityId(),player.getUserId()),UserMgr.getUserBaseInfo(player.getUserId(),GameServer.getInstance().getServerId())),false);
        DaFuWengMgr.syncUnionMemberDoll(player, null);
    }

    /**
     * 在线玩家下发配置
     */
    public static void onlinePlayerSendConfig() {
        DFWConfig dfwConfig = getDfwConfig();
        if (dfwConfig == null || ActivityMgr.activityInTime(dfwConfig.getActivityInfo())) {
            for (GamePlayer player : GamePlayerMgr.getCopyPlayerMap().values()) {
                syncDataAndConfig(player);
            }
        }
    }

    /**
     * 是否是密道事件
     */
    public static boolean isSecretRoadEvent(DFWUserData dfwUserData) {
        DFWConfig dfwConfig = getDfwConfig();
        if (dfwConfig == null) {
            return false;
        }
        if (dfwUserData == null) {
            return false;
        }
        int eventId = dfwUserData.getEventId();
        DFWEvent dfwEvent = dfwConfig.getDfwEventMap().get(eventId);
        return dfwEvent != null && dfwEvent.getEventType() == eDaFuWengEventType.Secret && !dfwUserData.isComplete() && dfwUserData.getUserSecretRoadList().size() > 0;
    }

    /**
     * 检查分组资格
     */
    public static int checkGroup(long userId) {
        if (dfwConfig == null || !ActivityMgr.activityInShowTime(dfwConfig.getActivityInfo())) {
            return GameErrorCode.E_ACTIVITY_DFW_NO_IN_TIME;
        }
        int activityId = dfwConfig.getActivityInfo().getActivityId();
        int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, userId);

        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID) {
            if (GameUnionActivityGroupMgr.haveGroup(activityId)) {
                return GameErrorCode.E_UNION_ACTIVITY_GROUP_NO_ABLE;
            } else {
                return GameErrorCode.E_UNION_ACTIVITY_GROUP_WAIT_GROUP;
            }
        }

        return 0;
    }

    /**
     * 获取玩家数据Builder
     * （部分协议有错误码时也要有这个，如果有数据就给他返回吧）
     */
    public static MonopolyProto.UserDataMsg.Builder getUserDataBuilder(long userId) {
        if (dfwConfig == null || !ActivityMgr.activityInShowTime(dfwConfig.getActivityInfo())) {
            return null;
        }
        DFWUserData userData = getUserData(dfwConfig.getActivityInfo().getActivityId(), userId);
        return DaFuWengPb.getUserDataMsg(userData);
    }
}
